美文网首页Python
Python爬虫--BeautifulSoup(三)

Python爬虫--BeautifulSoup(三)

作者: 无剑_君 | 来源:发表于2019-12-05 09:21 被阅读0次

    一、Beautiful Soup简介

      Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据。
    官方解释如下:
      Beautiful Soup提供一些简单的、python式的函数用来处理导航、搜索、修改分析等功能。它是一个工具箱,通过解析文档为用户提供需要抓取的数据,因为简单,所以不需要多少代码就可以写出一个完整的应用程序。
      Beautiful Soup自动将输入文档转换为Unicode编码,输出文档转换为utf-8编码。你不需要考虑编码方式,除非文档没有指定一个编码方式,这时,Beautiful Soup就不能自动识别编码方式了。然后,你仅仅需要说明一下原始编码方式就可以了。
      Beautiful Soup已成为和lxml、html5lib一样出色的python解释器,为用户灵活地提供不同的解析策略或强劲的速度。
      BeautifulSoup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,如果我们不安装它,则 Python 会使用 Python默认的解析器,lxml 解析器更加强大,速度更快,推荐使用lxml 解析器。
    官网文档:https://beautifulsoup.readthedocs.io/zh_CN/latest/
    BeautifulSoup4主要解析器:

    解析器 使用方法 优势 劣势
    Python标准库 BeautifulSoup(markup, "html.parser") Python内置标准库
    执行速度适中
    文档容错能力强
    Python 2.7.3 and 3.2.2 之前的版本容错能力差
    lxml HTML 解析器 BeautifulSoup(markup, "lxml") 速度快
    容错能力强
    需安装C语言库
    lxml XML 解析器 BeautifulSoup(markup, "lxml-xml")
    BeautifulSoup(markup,"xml")
    速度快
    唯一支持xml解析
    需安装C语言库
    html5lib 解析器 BeautifulSoup(markup, "html5lib") 最好的容错方式
    以浏览器的方式解析文档
    生成HTML5格式的文档
    速度慢,不 依赖外部扩展

    二、模块安装

    需安装:lxml模块
    注意:4.3.2 没有集成 etree
    请安装3.7.2:

    (film) C:\Users\Administrator>conda install lxml==3.7.2
    # 安装lxml
    pip install lxml
    # 2.x+版本
    pip install BeautifulSoup
    # 3.x+请安装以下版本
    pip install beautifulsoup4
    
    

    二、BeautifulSoup4使用

    假设有这样一个Html,具体内容如下:

    <!DOCTYPE html>
    <html>
    <head>
        <meta content="text/html;charset=utf-8" http-equiv="content-type" />
        <meta content="IE=Edge" http-equiv="X-UA-Compatible" />
        <meta content="always" name="referrer" />
        <link href="https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css" rel="stylesheet" type="text/css" />
        <title>百度一下,你就知道 </title>
    </head>
    <body link="#0000cc">
      <div id="wrapper">
        <div id="head">
            <div class="head_wrapper">
              <div id="u1">
                <a class="mnav" href="http://news.baidu.com" name="tj_trnews">新闻 </a>
                <a class="mnav" href="https://www.hao123.com" name="tj_trhao123">hao123 </a>
                <a class="mnav" href="http://map.baidu.com" name="tj_trmap">地图 </a>
                <a class="mnav" href="http://v.baidu.com" name="tj_trvideo">视频 </a>
                <a class="mnav" href="http://tieba.baidu.com" name="tj_trtieba">贴吧 </a>
                <a class="bri" href="//www.baidu.com/more/" name="tj_briicon" style="display: block;">更多产品 </a>
              </div>
            </div>
        </div>
      </div>
    </body>
    </html>
    

    创建beautifulsoup4对象并获取内容:

    from bs4 import BeautifulSoup
    
    file = open('./index.html', 'rb')
    html = file.read()
    bs = BeautifulSoup(html,"html.parser")
    print(bs.prettify())     # 缩进格式
    print(bs.title)          # 获取title标签的所有内容
    print(bs.title.name)     # 获取title标签的名称
    print(bs.title.string)   # 获取title标签的文本内容
    print(bs.head)           # 获取head标签的所有内容
    print(bs.div)            # 获取第一个div标签中的所有内容
    print(bs.div["id"])      # 获取第一个div标签的id的值
    print(bs.a)              # 获取第一个a标签中的所有内容
    print(bs.find_all("a"))  # 获取所有的a标签中的所有内容
    print(bs.find(id="u1"))   # 获取id="u1"
    for item in bs.find_all("a"):
        print(item.get("href")) # 获取所有的a标签,并遍历打印a标签中的href的值
    for item in bs.find_all("a"):
        print(item.get_text())# 获取所有的a标签,并遍历打印a标签的文本值
    
    

    三、BeautifulSoup4四大对象种类

    BeautifulSoup4将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种:
    Tag
    NavigableString
    BeautifulSoup
    Comment

    1. Tag

    Tag通俗点讲就是HTML中的一个个标签,例如:

    from bs4 import BeautifulSoup
    
    file = open('./index.html', 'rb')
    html = file.read()
    bs = BeautifulSoup(html,"html.parser")
    
    # 获取title标签的所有内容
    print(bs.title)
    
    # 获取head标签的所有内容
    print(bs.head)
    
    # 获取第一个a标签的所有内容
    print(bs.a)
    
    # 类型
    print(type(bs.a))
    
    

    可以利用 soup 加标签名轻松地获取这些标签的内容,这些对象的类型是bs4.element.Tag。
    但是注意,它查找的是在所有内容中的第一个符合要求的标签。
    对于 Tag,它有两个重要的属性,是nameattrs

    from bs4 import BeautifulSoup
    
    file = open('./index.html', 'rb')
    html = file.read()
    bs = BeautifulSoup(html,"html.parser")
    
    # [document] #bs 对象本身比较特殊,它的 name 即为 [document]
    print(bs.name)
    # head #对于其他内部标签,输出的值便为标签本身的名称
    print(bs.head.name)
    # 在这里,我们把 a 标签的所有属性打印输出了出来,得到的类型是一个字典。
    print(bs.a.attrs)
    # 还可以利用get方法,传入属性的名称,二者是等价的
    print(bs.a['class']) # 等价 bs.a.get('class')
    # 可以对这些属性和内容等等进行修改
    bs.a['class'] = "newClass"
    print(bs.a)
    # 还可以对这个属性进行删除
    del bs.a['class']
    print(bs.a)
    
    

    2. NavigableString

    获取标签内部的文字,用 .string 即可。

    from bs4 import BeautifulSoup
    
    file = open('./index.html', 'rb')
    html = file.read()
    bs = BeautifulSoup(html,"html.parser")
    
    print(bs.title.string)
    print(type(bs.title.string))
    
    

    3. BeautifulSoup

    BeautifulSoup对象表示的是一个文档的内容。大部分时候,可以把它当作 Tag 对象,是一个特殊的 Tag,我们可以分别获取它的类型,名称,以及属性:

    from bs4 import BeautifulSoup
    
    file = open('./index.html', 'rb')
    html = file.read()
    bs = BeautifulSoup(html,"html.parser")
    
    print(type(bs.name))
    print(bs.name)
    print(bs.attrs)
    
    

    4. Comment

    Comment 对象是一个特殊类型的 NavigableString 对象,其输出的内容不包括注释符号。

    from bs4 import BeautifulSoup
    
    file = open('./index.html', 'rb')
    html = file.read()
    bs = BeautifulSoup(html,"html.parser")
    
    print(bs.a)
    # 此时不能出现空格和换行符,a标签如下:
    # <a class="mnav" href="http://news.baidu.com" name="tj_trnews"><!--新闻--></a>
    print(bs.a.string)          # 新闻
    print(type(bs.a.string))    # <class 'bs4.element.Comment'>
    
    

    四、遍历文档树

    1. contents:获取Tag的所有子节点,返回一个list

    from bs4 import BeautifulSoup
    
    file = open('./index.html', 'rb')
    html = file.read()
    bs = BeautifulSoup(html,"html.parser")
    
    # tag的.content 属性可以将tag的子节点以列表的方式输出
    print(bs.head.contents)
    # 用列表索引来获取它的某一个元素
    print(bs.head.contents[1])
    
    

    2. .children:获取Tag的所有子节点,返回一个生成器

    from bs4 import BeautifulSoup
    
    file = open('./index.html', 'rb')
    html = file.read()
    bs = BeautifulSoup(html,"html.parser")
    
    for child in  bs.body.children:
        print(child)
    
    

    3. .descendants:获取Tag的所有子孙节点

    4. .strings:如果Tag包含多个字符串,即在子孙节点中有内容,可以用此获取,而后进行遍历

    5. .stripped_strings:与strings用法一致,只不过可以去除掉那些多余的空白内容

    6. .parent:获取Tag的父节点

    7. .parents:递归得到父辈元素的所有节点,返回一个生成器

    8. .previous_sibling:获取当前Tag的上一个节点,属性通常是字符串或空白,真实结果是当前标签与上一个标签之间的顿号和换行符

    9、.next_sibling:获取当前Tag的下一个节点,属性通常是字符串或空白,真是结果是当前标签与下一个标签之间的顿号与换行符

    10. .previous_siblings:获取当前Tag的上面所有的兄弟节点,返回一个生成器

    11. .next_siblings:获取当前Tag的下面所有的兄弟节点,返回一个生成器

    12. .previous_element:获取解析过程中上一个被解析的对象(字符串或tag),可能与previous_sibling相同,但通常是不一样的

    13. .next_element:获取解析过程中下一个被解析的对象(字符串或tag),可能与next_sibling相同,但通常是不一样的

    14. .previous_elements:返回一个生成器,可以向前访问文档的解析内容

    15. .next_elements:返回一个生成器,可以向后访问文档的解析内容

    16. .has_attr:判断Tag是否包含属性

    五、搜索文档树

    1. find_all(name, attrs, recursive, text, **kwargs)
        在上面的栗子中我们简单介绍了find_all的使用,接下来介绍一下find_all的更多用法-过滤器。这些过滤器贯穿整个搜索API,过滤器可以被用在tag的name中,节点的属性等。
      (1)name参数:
      字符串过滤:会查找与字符串完全匹配的内容:
    from bs4 import BeautifulSoup
    
    file = open('./index.html', 'rb')
    html = file.read()
    bs = BeautifulSoup(html,"html.parser")
    
    a_list = bs.find_all("a")
    print(a_list)
    
    

    正则表达式过滤:如果传入的是正则表达式,那么BeautifulSoup4会通过search()来匹配内容

    from bs4 import BeautifulSoup
    # 正则表达式
    import re
    
    file = open('./index.html', 'rb')
    html = file.read()
    bs = BeautifulSoup(html,"html.parser")
    
    t_list = bs.find_all(re.compile("a"))
    for item in t_list:
       print(item)
    
    

    列表:如果传入一个列表,BeautifulSoup4将会与列表中的任一元素匹配到的节点返回

    from bs4 import BeautifulSoup
    
    file = open('./index.html', 'rb')
    html = file.read()
    bs = BeautifulSoup(html,"html.parser")
    
    t_list = bs.find_all(["meta","link"])
    for item in t_list:
        print(item)
    
    

    方法:传入一个方法,根据方法来匹配

    from bs4 import BeautifulSoup
    
    file = open('./index.html', 'rb')
    html = file.read()
    bs = BeautifulSoup(html,"html.parser")
    
    # 定义函数
    def name_is_exists(tag):
        return tag.has_attr("name")
    
    # 使用函数
    t_list = bs.find_all(name_is_exists)
    for item in t_list:
        print(item)
    
    

    (2)kwargs参数:

    from bs4 import BeautifulSoup
    import re
    
    file = open('./index.html', 'rb')
    html = file.read()
    bs = BeautifulSoup(html,"html.parser")
    
    # 查询id=head的Tag
    t_list = bs.find_all(id="head")
    print(t_list)
    # 查询href属性包含ss1.bdstatic.com的Tag
    t_list = bs.find_all(href=re.compile("http://news.baidu.com"))
    print(t_list)
    # 查询所有包含class的Tag(注意:class在Python中属于关键字,所以加_以示区别)
    t_list = bs.find_all(class_=True)
    for item in t_list:
        print(item)
    
    

    (3)attrs参数:
    并不是所有的属性都可以使用上面这种方式进行搜索,比如HTML的data-*属性:

    t_list = bs.find_all(data-foo="value")
    

    如果执行这段代码,将会报错。我们可以使用attrs参数,定义一个字典来搜索包含特殊属性的tag:

    from bs4 import BeautifulSoup
    import re
    
    file = open('./index.html', 'rb')
    html = file.read()
    bs = BeautifulSoup(html,"html.parser")
    
    t_list = bs.find_all(attrs={"data-foo":"value"})
    for item in t_list:
        print(item)
    
    

    (4)text参数:
    通过text参数可以搜索文档中的字符串内容,与name参数的可选值一样,text参数接受 字符串,正则表达式,列表:

    from bs4 import BeautifulSoup
    import re
    
    file = open('./index.html', 'rb')
    html = file.read()
    bs = BeautifulSoup(html,"html.parser")
    
    t_list = bs.find_all(attrs={"data-foo": "value"})
    for item in t_list:
        print(item)
    t_list = bs.find_all(text="hao123")
    for item in t_list:
        print(item)
    t_list = bs.find_all(text=["hao123", "地图", "贴吧"])
    for item in t_list:
        print(item)
    t_list = bs.find_all(text=re.compile("\d"))
    for item in t_list:
        print(item)
    
    

    当我们搜索text中的一些特殊属性时,同样也可以传入一个方法来达到我们的目的:

    from bs4 import BeautifulSoup
    import re
    
    file = open('./index.html', 'rb')
    html = file.read()
    bs = BeautifulSoup(html,"html.parser")
    
    # 定义函灵敏
    def length_is_two(text):
        return text and len(text) == 2
    
    t_list = bs.find_all(text=length_is_two)
    for item in t_list:
        print(item)
    
    

    (5)limit参数:
    可以传入一个limit参数来限制返回的数量,当搜索出的数据量为5,而设置了limit=2时,此时只会返回前2个数据:

    from bs4 import BeautifulSoup
    import re
    
    file = open('./index.html', 'rb')
    html = file.read()
    bs = BeautifulSoup(html,"html.parser")
    
    t_list = bs.find_all("a",limit=2)
    for item in t_list:
        print(item)
    
    

    find_all除了上面一些常规的写法,还可以对其进行一些简写:

    from bs4 import BeautifulSoup
    import re
    
    file = open('./index.html', 'rb')
    html = file.read()
    bs = BeautifulSoup(html,"html.parser")
    
    # 两者是相等的
    # t_list = bs.find_all("a") => t_list = bs("a")
    t_list = bs("a") # 两者是相等的
    # t_list = bs.a.find_all(text="新闻") => t_list = bs.a(text="新闻")
    t_list = bs.a(text="新闻")
    
    

    2. find()

    find()将返回符合条件的第一个Tag,有时我们只需要或一个Tag时,我们就可以用到find()方法了。当然了,也可以使用find_all()方法,传入一个limit=1,然后再取出第一个值也是可以的,不过未免繁琐。

    from bs4 import BeautifulSoup
    import re
    
    file = open('./index.html', 'rb')
    html = file.read()
    bs = BeautifulSoup(html,"html.parser")
    
    # 返回只有一个结果的列表
    t_list = bs.find_all("title",limit=1)
    print(t_list)
    # 返回唯一值
    t = bs.find("title")
    print(t)
    # 如果没有找到,则返回None
    t = bs.find("abc")
    print(t)
    
    

    从结果可以看出find_all,尽管传入了limit=1,但是返回值仍然为一个列表,当我们只需要取一个值时,远不如find方法方便。但是如果未搜索到值时,将返回一个None

    可以通过bs.div来获取第一个div标签,如果我们需要获取第一个div下的第一个div,我们可以这样:

    from bs4 import BeautifulSoup
    import re
    
    file = open('./index.html', 'rb')
    html = file.read()
    bs = BeautifulSoup(html,"html.parser")
    
    t = bs.div.div
    # 等价于
    t = bs.find("div").find("div")
    print(t)
    
    

    六、CSS选择器

    BeautifulSoup支持发部分的CSS选择器,在Tag获取BeautifulSoup对象的.select()方法中传入字符串参数,即可使用CSS选择器的语法找到Tag:

    1. 通过标签名查找
    from bs4 import BeautifulSoup
    import re
    
    file = open('./index.html', 'rb')
    html = file.read()
    bs = BeautifulSoup(html,"html.parser")
    
    print(bs.select('title'))
    print(bs.select('a'))
    
    1. 通过类名查找
    from bs4 import BeautifulSoup
    import re
    
    file = open('./index.html', 'rb')
    html = file.read()
    bs = BeautifulSoup(html,"html.parser")
    
    print(bs.select('.mnav'))
    
    
    1. 通过id查找
    from bs4 import BeautifulSoup
    import re
    
    file = open('./index.html', 'rb')
    html = file.read()
    bs = BeautifulSoup(html,"html.parser")
    
    print(bs.select('#u1'))
    
    
    1. 组合查找
    from bs4 import BeautifulSoup
    import re
    
    file = open('./index.html', 'rb')
    html = file.read()
    bs = BeautifulSoup(html,"html.parser")
    
    print(bs.select('div .bri'))
    
    
    1. 属性查找
    from bs4 import BeautifulSoup
    import re
    
    file = open('./index.html', 'rb')
    html = file.read()
    bs = BeautifulSoup(html,"html.parser")
    
    print(bs.select('a[class="bri"]'))
    print(bs.select('a[href="http://tieba.baidu.com"]'))
    
    
    1. 直接子标签查找
    from bs4 import BeautifulSoup
    import re
    
    file = open('./index.html', 'rb')
    html = file.read()
    bs = BeautifulSoup(html,"html.parser")
    
    t_list = bs.select("head > title")
    print(t_list)
    
    
    1. 兄弟节点标签查找
    from bs4 import BeautifulSoup
    import re
    
    file = open('./index.html', 'rb')
    html = file.read()
    bs = BeautifulSoup(html,"html.parser")
    
    t_list = bs.select(".mnav ~ .bri")
    print(t_list)
    
    1. 获取内容
    from bs4 import BeautifulSoup
    import re
    
    file = open('./index.html', 'rb')
    html = file.read()
    bs = BeautifulSoup(html,"html.parser")
    
    t_list = bs.select("title")
    print(bs.select('title')[0].get_text())
    
    

    七、示例

    1. BeautifulSoup 解析58同城网
    #encoding:UTF-8
    from bs4 import BeautifulSoup
    import requests
    import time
    import json
     
    url = 'http://bj.58.com/pingbandiannao/24604629984324x.shtml'
     
    wb_data = requests.get(url)
    soup = BeautifulSoup(wb_data.text,'lxml')
     
    #获取每件商品的URL
    def get_links_from(who_sells):
        urls = []
        list_view = 'http://bj.58.com/pbdn/pn{}/'.format(str(who_sells))
        print ('list_view:{}'.format(list_view) )
        wb_data = requests.get(list_view)
        soup = BeautifulSoup(wb_data.text,'lxml')
        #for link in soup.select('td.t > a.t'):
        for link in soup.select('td.t  a.t'):  #跟上面的方法等价
            print link
            urls.append(link.get('href').split('?')[0])
        return urls
      
    #获取58同城每一类商品的url  比如平板电脑  手机 等
    def get_classify_url():
        url58 = 'http://bj.58.com'
        wb_data = requests.get(url58)
        soup = BeautifulSoup(wb_data.text, 'lxml')
        for link in soup.select('span.jumpBusiness a'):
            classify_href = link.get('href')
            print classify_href
            classify_url = url58 + classify_href
            print classify_url
     
    #获取每件商品的具体信息
    def get_item_info(who_sells=0):
     
        urls = get_links_from(who_sells)
        for url in urls:
            print url
            wb_data = requests.get(url)
            #print wb_data.text
            soup = BeautifulSoup(wb_data.text,'lxml')
            #print soup.select('infolist > div > table > tbody > tr.article-info > td.t > span.pricebiao > span')   ##infolist > div > table > tbody > tr.article-info > td.t > span.pricebiao > span
            print soup.select('span[class="price_now"]')[0].text
            print soup.select('div[class="palce_li"]')[0].text
            #print list(soup.select('.palce_li')[0].stripped_strings) if soup.find_all('div','palce_li') else None,  #body > div > div > div > div > div.info_massege.left > div.palce_li > span > i
            data = {
                'title':soup.title.text,
                'price': soup.select('span[class="price_now"]')[0].text,
                'area': soup.select('div[class="palce_li"]')[0].text if soup.find_all('div', 'palce_li') else None,
                'date' :soup.select('.look_time')[0].text,
                'cate' :'个人' if who_sells == 0 else '商家',
            }
            print(data)
            result = json.dumps(data, encoding='UTF-8', ensure_ascii=False) #中文内容仍然无法正常显示。 使用json进行格式转换,然后打印输出。
            print result
     
    # get_item_info(url)
     
    # get_links_from(1)
     
    get_item_info(2)
    #get_classify_url()
    
    
    1. 时光网电影票房 top 100
      Mtime时光网
      http://movie.mtime.com/boxoffice/
    # -*- coding:UTF-8 -*-
    
    from bs4 import BeautifulSoup
    import pandas as pd
    import requests
    
    """
    pandas 模块
    requests 模块
    BeautifulSoup 模块
    openpyxl 模块
    
    爬取时光网电影票房数据
    """
    def sgw(year):
        # 设置session
        s = requests.session()
        headers = {
            'Accept': '*/*',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Connection': 'keep-alive',
            'Host': 'movie.mtime.com',
            'Referer': 'http://movie.mtime.com/boxoffice/',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.15 Safari/537.36',
            'X-Requested-With': 'XMLHttpRequest',
        }
        # 更新头信息
        s.headers.update(headers)
        #
        df = pd.DataFrame(columns=('排名', '电影', '类型', '首日票房(元)', '年度票房(元)', '上映日期'))
        x = 0
    
        for i in range(10):
            # 两个参数 一个为年,一个为页
            url = 'http://movie.mtime.com/boxoffice/?year={}&area=china&type=MovieRankingYear&category=all&page={}&display=table&timestamp=1547015331595&version=07bb781100018dd58eafc3b35d42686804c6df8d&dataType=json'.format(
                year,str(i))
            req = s.get(url=url, verify=False).text
            bs = BeautifulSoup(req, 'lxml')
            tr = bs.find_all('tr')
            for j in tr[1:]:
                td = j.find_all('td')
                list = []
                for k in range(6):
                    if k == 1:
                        nm = td[k].find('a').text
                        print(td[k].a.string)
                        list.append(nm)
                    else:
                        list.append(td[k].text)
                df.loc[x] = list
                x = x + 1
        print(df)
        df.to_excel('时光网.xlsx', index=False, encoding="GB18030")
    
    # 调用方法
    sgw(2019)
    
    1. 豆瓣top250电影
      https://movie.douban.com/top250
    豆瓣top250电影
    # -*- coding: utf-8 -*-
    from bs4 import BeautifulSoup
    import requests
    
    '''
    requests 模块
    BeautifulSoup 模块
    lxml 模块
    豆瓣top250电影
    '''
    
    rank = 1
    def write_one_page(soup):
        global rank
        # 查找相应数据
        for k in soup.find('div',class_='article').find_all('div',class_='info'):
            name = k.find('div',class_='hd').find_all('span')       #电影名字
            score = k.find('div',class_='star').find_all('span')    #分数
    
            if k.find('p',class_='quote') != None :
                inq = k.find('p',class_='quote').find('span')           #一句话简介
    
            #抓取年份、国家
            actor_infos_html = k.find(class_='bd')
    
            #strip() 方法用于移除字符串头尾指定的字符(默认为空格)
            actor_infos = actor_infos_html.find('p').get_text().strip().split('\n')
            # \xa0 是不间断空白符 &nbsp;
            actor_infos1 = actor_infos[0].split('\xa0\xa0\xa0')
            director = actor_infos1[0][3:]
            role = actor_infos[1]
            year_area = actor_infos[1].lstrip().split('\xa0/\xa0')
            year = year_area[0]
            country = year_area[1]
            type = year_area[2]
            # 序号 电影名称 评分 简介 年份 地区  类型
            print(rank,name[0].string,score[1].string,inq.string,year,country,type)
            #写txt
            write_to_file(rank,name[0].string,score[1].string,year,country,type,inq.string)
            # 页数
            rank=rank+1
    # 写文件
    def write_to_file(rank,name,score,year,country,type,quote):
        with open('Top_250_movie.txt', 'a', encoding='utf-8') as f:
            f.write(str(rank)+';'+str(name)+';'+str(score)+';'+str(year)+';'+str(country)+';'+str(type)+';'+str(quote)+'\n')
            f.close()
    
    if __name__ == '__main__':
        for i in range(10):
            a = i*25
            # https://movie.douban.com/top250
            url = "https://movie.douban.com/top250?start="+str(a)+"&filter="
            f = requests.get(url)
            # 创建对象
            soup = BeautifulSoup(f.content, "lxml")
    
            write_one_page(soup)
    

    相关文章

      网友评论

        本文标题:Python爬虫--BeautifulSoup(三)

        本文链接:https://www.haomeiwen.com/subject/weqioqtx.html