美文网首页
python爬虫学习(四)

python爬虫学习(四)

作者: rrrwx | 来源:发表于2019-06-12 15:57 被阅读0次

    (一)BeautifulSoup库
    Beautiful Soup是python的一个库,主要功能是从网页抓取数据,也叫beaultifulsoup4或bs4。

    Beautiful Soup提供一些简单的、python式的函数用来处理导航、搜索、修改分析树等功能。它是一个工具箱,通过解析文档为用户提供需要抓取的数据,因为简单,所以不需要多少代码就可以写出一个完整的应用程序。

    import requests
    
    r = requests.get("https://python123.io/ws/demo.html")
    demo = r.text
    
    from bs4 import BeautifulSoup
    soup = BeautifulSoup(demo, "html.parser")
    print(soup.prettify())
    
    <html>
     <head>
      <title>
       This is a python demo page
      </title>
     </head>
     <body>
      <p class="title">
       <b>
        The demo python introduces several python courses.
       </b>
      </p>
      <p class="course">
       Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
       <a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">
        Basic Python
       </a>
       and
       <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">
        Advanced Python
       </a>
       .
      </p>
     </body>
    </html>
    

    (二)符号理解

    Tag: 标签,分别用<>和</>标明开始和结尾
    Name: 标签的名字,如<p>...</p>的名字是'p'
    Attributes: 标签的属性
    NavigableString: 标签内非属性字符串
    Comment: 标签内字符串的注释部分

    一段代码差不多明白了

    import requests
    
    r = requests.get("https://python123.io/ws/demo.html")
    demo = r.text
    
    from bs4 import BeautifulSoup
    soup = BeautifulSoup(demo, "html.parser")
    print(soup.title)
    print(soup.a)
    tag = soup.a
    print(tag.name)
    print(tag.attrs)
    print(tag.attrs['class'])
    print(tag.parent)
    print(tag.parent.name)
    print(tag.parent.parent)
    

    (三)遍历
    上行遍历: .contents, .children, .descendants
    下行遍历: .parent, .parents
    平行遍历: .next_sibling, .next_siblings, .previous_sibling, .previous_siblings

    import requests
    from bs4 import BeautifulSoup
    
    r = requests.get("https://python123.io/ws/demo.html")
    demo = r.text
    
    soup = BeautifulSoup(demo, "html.parser")
    for parent in soup.a.parents:
        if parent is None:
            print(parent)
        else:
            print(parent.name)
    

    (四)基于bs4的HTML内容提取
    话不多说,上代码

    soup = BeautifulSoup(demo, "html.parser")
    for link in soup.find_all('a'):
        print(link.get('href'))
    
    http://www.icourse163.org/course/BIT-268001
    http://www.icourse163.org/course/BIT-1001870001
    

    find_all函数里面可以是'a',也可以是['a', 'b']同时也可以使用正则表达式

    <>.find_all(name, attrs,)

    for tag in soup.find_all(True):
        print(tag.name)
    soup.find_all('p', 'course')
    soup.find_all(id = 'link1')
    import re
    soup.find_all(id = re.compile('b'))
    

    (五)实例

    import requests
    from bs4 import BeautifulSoup
    import bs4
    
    def getHTMLText(url):
        try:
            r = requests.get(url, timeout = 30)
            r.raise_for_status()
            r.encoding = r.apparent_encoding
            return r.text
        except:
            return ""
    
    def fillUnivList(ulist, html):
        soup = BeautifulSoup(html, "html.parser")
        for tr in soup.find('tbody').children:
            if isinstance(tr, bs4.element.Tag):
                tds = tr('td')
                ulist.append([tds[0].string, tds[1].string, tds[2].string])
    
    def printUnivList(ulist, num):
        tplt = "{0:^10}\t{1:{3}^10}\t{2:^10}"
        print(tplt.format("排名", "学校名称", "省份", chr(12288)))
        for i in range(num):
            u = ulist[i]
            print(tplt.format(u[0], u[1], u[1], chr(12288)))
    
    if __name__ == '__main__':
        uinfo = []
        url = "http://www.zuihaodaxue.com/zuihaodaxuepaiming2019.html"
        html = getHTMLText(url)
        fillUnivList(uinfo, html)
        printUnivList(uinfo, 20)
    

    结果

        排名         学校名称         省份    
        1          清华大学         北京    
        2          北京大学         北京    
        3          浙江大学         浙江    
        4         上海交通大学        上海    
        5          复旦大学         上海    
        6        中国科学技术大学       安徽    
        7         华中科技大学        湖北    
        7          南京大学         江苏    
        9          中山大学         广东    
        10       哈尔滨工业大学       黑龙江    
        11       北京航空航天大学       北京    
        12         武汉大学         湖北    
        13         同济大学         上海    
        14        西安交通大学        陕西    
        15         四川大学         四川    
        16        北京理工大学        北京    
        17         东南大学         江苏    
        18         南开大学         天津    
        19         天津大学         天津    
        20        华南理工大学        广东    
    

    相关文章

      网友评论

          本文标题:python爬虫学习(四)

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