Beautifu Soup库一个非常优秀的Python第三方库,可以很好地对HTML进行解析并且提取其中的信息。主要负责解析、遍历、维护“标签树”。
以管理员命令运行cmd=>pip install beautifulsoup4
这里注意后面有个4,这是最新的版本。详细可以参考Beautiful Soup的官网
>>> import requests
>>> r = requests.get('http://python123.io/ws/demo.html')
>>> r.text
'...` # 这里省略了内容
>>> demo = r.text
>>> from bs4 import BeautifulSoup # 这个导入需要注意
>>> soup = BeautifulSoup(demo,'html.parser') # 可以用help(BeautifulSop)查看帮助文档
>>> print(soup.prettify())
`...` # 这里省略了内容
Beautiful Soup库就是一个工具,可以从被标记的信息中识别出来标记信息,从而精准的提取你需要的信息。
Beautiful Soup库,也叫beautifulsoup4 或bs4,约定引用方式如下,即主要是用BeautifulSoup类
# 第一种用的最为频繁
from bs4 import BeautifulSoup
# 第二种
import bs4
BeautifulSoup类,BeautifulSoup对应一个HTML/XML文档的全部内容。
任何存在于HTML语法中的标签都可以用soup.访问获得,当HTML文档中存在多个相同对应内容时,soup.返回第一个。
>>> soup.title
<title>This is a python demo page</title>
>>> tag = soup.a
>>> print(tag)
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>
的名字是’p’,格式:.name
每个tag都有自己的名字,通过.name获取,字符串类型。
>>> soup.a.name
'a'
>>> soup.a.parent.name
'p'
>>> soup.a.parent.parent.name
'body'
一个可以有0或多个属性,返回一个字典,属于字典类型。
>>> 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'>
NavigableString可以跨越多个层次,前提是只有一个字符串子串,多余一个子串则也返回None.
help文档里面解释是:
string
| Convenience property to get the single string within this tag.
|
| :Return: If this tag has a single string child, return value
| is that string. If this tag has no children, or more than one
| child, return value is None. If this tag has one child tag,
| return value is the ‘string’ attribute of the child tag,
| recursively.
>>> soup.a
<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>
>>> 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'>
Comment是一种特殊类型。
>>> newsoup = BeautifulSoup("This is not a comment
","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'> # 非注释的字符串类型
官方help文档,常与字符串的split()方法联用来分割得到需要的部分。
text
| Get all child strings, concatenated using the given separator.
>>> soup.h1.text
'\n\n 中国中车 (601766)\n \n已收盘 2019-01-23 \xa015:01:28\n \n'
基于bs4库的HTML内容遍历方法主要分为三种:下行遍历、上行遍历、平行遍历。
标签树的下行遍历的三个属性:
# 遍历儿子节点
for child in soup.body.children:
print(child)
# 遍历子孙节点
for child in soup.body.descendants:
print(child)
实例演示:
>>> soup.head # 查看标签
<head><title>This is a python demo page</title></head>
>>> soup.head.contents # 查看head标签的内容,注意这里返回的是一个列表,所以可以对返回到列表执行列表操作
[<title>This is a python demo page</title>]
>>> soup.body.contents # 获得body标签的内容列表
['\n', <p class="title"><b>The demo python introduces several python courses.</b></p>, '\n', <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>, '\n']
>>> len(soup.body.contents) # 获取列表的元素个数,注意这里的'\n'也算一个元素
5
>>> soup.body.contents[1] # 查看列表的第二个元素
<p class="title"><b>The demo python introduces several python courses.</b></p>
标签树的上行遍历主要包含两个属性:
>>> soup.title.parent
<head><title>This is a python demo page</title></head>
>>> soup.html.parent
<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>
>>> soup.parent # soup的父亲是空的
# 对Soup.a标签的所有父辈标签名字进行打印
>>> for parent in soup.a.parents: # 标签树的上行代码遍历
if parent is None: # 因为会遍历到最上面的soup,但是soup没有标签名,所以要区分对待
print(parent)
else:
print(parent.name)
p
body
html
[document]
标签树的平行遍历有四个属性:
# 遍历后续平行节点
for sibling in soup.a.next_sibling:
print(sibling)
# 遍历前续平行节点
for sibling in soup.a.previous_sibling:
print(sibling)
实例:
>>> soup.a.next_sibling # 注意这里得到的不是标签,而是字符串,所以需要做判断处理
' and '
>>> soup.a.next_sibling.next_sibling
<a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">Advanced Python</a>
>>> soup.a.previous_sibling
'Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:\r\n'
>>> soup.a.previous_sibling.previous_sibling
>>> soup.a.parent
<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>
prettify()方法能够让HTML的内容更加友好的显示出来便于我们分析网页,从而发现规律。
.prettify()为HTML文本<>及其内容增加’\n’
.prettify()可用于标签,方法:.prettify()
bs4库将任何HTML输入都变成utf‐8编码
Python 3.x默认支持编码是utf‐8,解析无障碍
实例如下:
>>> soup.prettify()
'\n \n \n This is a python demo page\n \n \n \n \n \n The demo python introduces several python courses.\n \n
\n \n Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:\n \n Basic Python\n \n and\n \n Advanced Python\n \n .\n
\n \n'
>>> 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>
<>.find_all(name, attrs, recursive, string, **kwargs)——返回一个列表类型,存储查找的结果
# 1. name: 对标签名称的检索字符串
>>> 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>]
>>> soup.find_all(['a','b']) # 传入一个列表,实现同时检索出列表里面两个或者多个标签的内容
[<b>The demo python introduces several python courses.</b>, <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>]
>>> for tag in soup.find_all(True):
print(tag.name)
html
head
title
body
p
b
p
a
a
# 实现同时检索出b标签和包含b字符的body标签,需要引入正则表达式re模块
>>> import re
>>> for tag in soup.find_all(re.compile('b')):
print(tag.name)
body
b
# 2. attrs: 对标签属性值的检索字符串,可标注属性检索
>>> soup.find_all('p','course')
[<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>]
>>> soup.find_all(id = 'link1')
[<a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">Basic Python</a>]
>>> soup.find_all(id='link') # 需要完全匹配,所以匹配不到link,返回空列表
[]
>>> soup.find_all(id=re.compile('link')) # 通过正则表达式实现部分匹配
[<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>]
# 3. recursive: 是否对子孙全部检索,默认True
>>> soup.find_all('a') # 返回包括子孙节点在内的所有‘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>]
>>> soup.find_all('a',recursive=False) # 可以看到在soup这个平行节点中,没有找到a标签,所以a标签在soup的子孙节点
[]
# 4. string: <>…>中字符串区域的检索字符串
>>> soup.find_all(string = 'Basic Python') # 完全匹配检索Basic Python
['Basic Python']
>>> soup.find_all(string = re.compile("python")) # 使用re模块的正则表达式实现部分匹配,所以re和find_all()结合使用,功能强大
['This is a python demo page', 'The demo python introduces several python courses.']
注意:
(…) 等价于.find_all(…)
soup(…) 等价于soup.find_all(…)
扩展方法:
北京理工大学嵩天老师的《Python网络爬虫与信息提取》