Python旅途遇到游乐园——爬虫入门 ( 二 )

我想我应该告诉你们我又干了什么憨批事

今天来玩BeautifulSoup库
我们之前已经学会了用Requests库进行简单的爬取,复习一下:

import requests
url = 'http://python123.io/ws/demo.html'
try:
    r = requests.get(url)
    r.raise_for_status()
    # 异常处理
    r.encoding = r.apparent_encoding  # 记住ta
    print(r.text[:1000])
except:
    print('爬取失败')

今天我们要接触的BeautifulSoup库,是编写Python爬虫常用库之一,主要用来解析html标签
我们可以先来试验一下:

import requests
from bs4 import BeautifulSoup
url = 'http://python123.io/ws/demo.html'
r = requests.get(url)
demo = r.text
soup = BeautifulSoup(demo , 'html.parser')
print(soup.prettify)

精简一下,BeautifulSoup的使用方法就是两句话:

from bs4 import BeautifulSoup
soup = BeautifulSoup('<p>data</p>' , 'html.parser')

开局我们从bs4库中引入了一个BeautifulSoup类型
BeautifulSoup类型有两个参数:

  • '<p>data</p>':html格式的信息
  • 'html.parser':解析器(在这里我们选择了html.parser)

BeautifulSoup库的基本元素

任何一个html文件,都是由若干个尖括号构成的标签组织起来的
而BeautifulSoup库是解析,遍历,维护 " 标签树 " 的功能库
只要提供的文件是标签类型,BeautifulSoup库就可以对其进行解析

html标签:
< p > . . < / p > : T a g <p>..</p>:标签Tag
< p   c l a s s = " t i t l e " > . . . < / p > <p\ class="title">...</p>

  • 名称Name成对出现:p ⬅➡ /p
  • 属性Attributes有0个或多个:class=“title”

BeautifulSoup库解析器

解析器 使用方法 条件
bs4的HTML解析器 BeautifulSoup(mk,‘html.parser’) pip install beautifulsoup4
Ixml的HTML解析器 BeautifulSoup(mk,‘lxml’) pip install lxml
lxml的XML解析器 BeautifuSoup(mk,‘xml’) pip install lxml
html5lib解析器 BeautifulSoup(mk,‘html5lib’) pip install html5lib

BeautifulSoup库的基本元素

基本元素 说明
Tag 标签,最基本的信息组织单元,分别用< >和< / >标明开头和结尾
Name 标签的名字,< p >…< /p >的名字是‘p’,格式:< tag >.name
Attributes 标签的属性,字典形式组织,格式:< tag >.attrs
NavigableString 标签内非属性字符串,< >…< / >中的字符串,格式:< tag >.string
Comment 标签内字符串的注释部分,一种特殊的Comment类型

在这里插入图片描述

import requests
from bs4 import BeautifulSoup
url = 'http://python123.io/ws/demo.html'
r = requests.get(url)
demo = r.text
soup = BeautifulSoup(demo , "html.parser")

>>> soup.title
<title>This is a python demo page</title>

>>> soup.a.name
'a'
>>> soup.a.parent.name
'p'
>>> soup.a.parent.parent.name
'body'

>>> soup.a
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>
>>> tag = soup.a
>>> tag.attrs
{'href': 'http://www.icourse163.org/course/BIT-268001', 'class': ['py1'], 'id': 'link1'}
>>> tag.attrs['class']
['py1']
>>> tag.attrs['href']
'http://www.icourse163.org/course/BIT-268001'
>>> type(tag.attrs)
<class 'dict'>
>>> type(tag)
<class 'bs4.element.Tag'>

>>> soup.a.string
'Basic Python'
>>> soup.p
<p class="title"><b>The demo python introduces several python courses.</b></p>
>>> soup.p.string
'The demo python introduces several python courses.'
>>> type(soup.p.string)
<class 'bs4.element.NavigableString'>

>>> newsoup = BeautifulSoup('<b><!--This is a comment--></b><p>This is not a comment</p>','html.parser')
>>> newsoup.b.string
'This is a comment'
>>> type(newsoup.b.string)
<class 'bs4.element.Comment'>
>>> newsoup.p.string
'This is not a comment'
>>> type(newsoup.p.string)
<class 'bs4.element.NavigableString'>

基于bs4库的HTML内容遍历方法

首先介绍HTML基本格式
在这里插入图片描述

标签树的下行遍历

属性 说明
.contents 子节点的列表,将< tag >所有儿子节点存入列表
.children 子节点的迭代类型,与.contents类似,用于循环遍历儿子节点
.descendants 子孙节点的迭代类型,包含所有子孙节点,用于循环遍历
import requests
from bs4 import BeautifulSoup
url = 'http://python123.io/ws/demo.html'
r = requests.get(url)
demo = r.text
soup = BeautifulSoup(demo , "html.parser")

>>> soup.head
<head><title>This is a python demo page</title></head>
>>> len(soup.body.contents)
5
>>> soup.body.contents[1]
<p class="title"><b>The demo python introduces several python courses.</b></p>
>>> 

遍历儿子:

for child in soup.body.children:
    print(child)

遍历子孙:

for child in soup.body.descendants:
    print(child)

标签树的上行遍历

属性 说明
.parent 节点的父亲节点
.parents 节点先辈标签的迭代类型,用于循环遍历先辈节点
>>> soup.title
<title>This is a python demo page</title>
>>> soup.title.parent
<head><title>This is a python demo page</title></head>
import requests
from bs4 import BeautifulSoup
url = 'http://python123.io/ws/demo.html'
r = requests.get(url)
demo = r.text
soup = BeautifulSoup(demo , "html.parser")
for parent in soup.a.parents:
    if parent is None:
        print(parent)
    else:
        print(parent.name)

##########################################

p
body
html
[document]

标签树的平行遍历

属性 说明
.next_sibling 返回按照HTML文本顺序的下一个平行节点标签
.previous_sibling 返回按照HTML文本顺序的上一个平行节点标签
.next_siblings 迭代类型,返回按照HTML文本顺序的后续所有平行节点标签
.previous_siblings 迭代类型,返回按照HTML文本顺序的前序所有平行节点标签

遍历后续节点:

for sibling in soup.a.next_siblings:
    print(sibling)

遍历前序节点:

for sibling in soup.a.previous_siblings:
    print(sibling)

总结一下

在这里插入图片描述


基于bs4库的HTML格式化和编码

prettify()

>>> soup.prettify()
'<html>\n <head>\n  <title>\n   This is a python demo page\n  </title>\n </head>\n <body>\n  <p class="title">\n   <b>\n    The demo python introduces several python courses.\n   </b>\n  </p>\n  <p class="course">\n   Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:\n   <a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">\n    Basic Python\n   </a>\n   and\n   <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">\n    Advanced Python\n   </a>\n   .\n  </p>\n </body>\n</html>'
>>> 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>

基于bs4库的HTML内容查找方法

<>.find_all(name,attrs,recursive,string,**kwargs)

返回一个列表类型,存储查找的结果

  • name:对标签名称的检索字符串
  • attrs:对标签属性值的检索字符串,可标注属性检索
  • recursive:是否对所有子孙进行检索,默认为True
  • string:<>…</>中字符串区域的检索字符串
>>> soup.find_all('a')
[<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>, <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>]

扩展方法:

方法 说明
.find() 搜索且只返回一个结果,字符串类型,同.find_all()参数
.find_parents() 在先辈节点中搜索,返回列表类型,同.find_all()参数
.find_parent() 在先辈节点中返回一个结果,字符串类型,同.find()参数
.find_next_sibling() 在后续平行节点中搜索,返回列表类型,同.find_all()参数
.find_next_siblings() 在后续平行节点中返回一个结果,字符串类型,同.find()参数
.find_previous_sibling() 在前序平行节点中搜索,返回列表类型,同.find_all()参数
.find_previous_siblings() 在前序平行节点中返回一个结果,字符串类型,同.find()参数

实例:中国大学排名定向爬虫

功能描述

输入:大学排名URL链接
输出:大学排名信息的屏幕输出(排名,大学名称,总分)
技术路线:requests-bs4
定向爬虫:仅对输入的URL进行爬取,不扩展爬取

这就是我们今天行动的目标
我们查看一下robots.txt,发现404了,那就甩开膀子爬吧

程序的结构设计

步骤一:从网站上获取大学排名网页内容( g e t H T M L T e x t ( ) getHTMLText()
步骤二:提取网站内容中信息到合适的数据结构( f i l l U n i v L i s t ( ) fillUnivList()
步骤三:利用数据结构展示并输出结果( p r i n t U n i v L i s t ( ) printUnivList()

import requests
from bs4 import BeautifulSoup
import bs4

def getHTMLText(url):  # 爬取模板
    try:
        r = requests.get(url)
        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:  # 通过阅读源代码得知信息都在tbody中
        if isinstance(tr,bs4.element.Tag):  # 过滤非Tag类型的信息
            tds = tr('td')
            ulist.append([tds[0].string , tds[1].string , tds[3].string])

def printUnivList(ulist,num):
    print('{:^10}\t{:^20}\t{:^10}'.format('排名','学校名称','总分'))
    for i in range(num):
        u = ulist[i]
        print('{:^10}\t{:^20}\t{:^10}'.format(u[0],u[1],u[2]))    

def main():
    uinfo = []
    url = 'http://www.zuihaodaxue.cn/zuihaodaxuepaiming2019.html'
    html = getHTMLText(url)
    fillUnivList(uinfo,html)
    printUnivList(uinfo,20)  # 20 univs

main()

在这里插入图片描述

文章的最后,简单解释一下这几行代码的用意:

for tr in soup.find('tbody').children:  # 通过阅读源代码得知信息都在tbody中
    if isinstance(tr,bs4.element.Tag):  # 过滤非Tag类型的信息
         tds = tr('td')
         ulist.append([tds[0].string , tds[1].string , tds[3].string])

通过阅读源代码,我们会发现我们需要的关键信息都在tbody之下 ( children ) 的tr标签
tr标签内找到所有的td标签,并存储为列表类型:tds = tr('td')(等价于tds = tr.find_all('td')
因为学校排名+学校名称+总分都是td标签的NavigableString,所以需要取tr标签的string
在这里插入图片描述

发布了964 篇原创文章 · 获赞 235 · 访问量 34万+

猜你喜欢

转载自blog.csdn.net/wu_tongtong/article/details/104392838