目录
一、Beautiful Soup库入门
1、Beautiful Soup库入门
(1)Beautiful Soup库的定义
解析HTML页面信息标记与提取方法。
(2)Beautiful Soup库的官网
https://www.crummy.com/software/BeautifulSoup/。
(3)Beautiful Soup库的安装
管理员权限启动cmd。
输入:
pip install beautifulsoup4
备注:直接安装Anaconda,更加方便。(https://blog.csdn.net/wyatt007/article/details/80369755)
(4)Beautiful Soup库的安装小测
演示HTML页面地址:https://python123.io/ws/demo.html。
页面源代码:HTML5.0格式代码。
<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 href="http://www.icourse163.org/course/BIT-268001" class="py1" id="link1">Basic Python</a> and <a href="http://www.icourse163.org/course/BIT-1001870001" class="py2" id="link2">Advanced Python</a>.</p>
</body></html>
# Beautiful Soup库的安装小测
from bs4 import BeautifulSoup
soup = BeautifulSoup('<p>data</p>', "html.parser") # BeautifulSoup是一个类,第一个参数是需要BeautifulSoup解析的html信息,第二个参数是需要用的解析器。
# Beautiful Soup库的安装小测全代码
import requests
r = requests.get("http://python123.io/ws/demo.html")
r.text
print(r.text)
demo = r.text
from bs4 import BeautifulSoup
soup = BeautifulSoup(demo, "html.parser")
print(soup.prettify())
2、Beautiful Soup库的基本元素
(1)Beautiful Soup库的理解
Beautiful Soup库是解析、遍历、维护“标签树”的功能库。
<html>
<body>
<p class="title"> ... </p>
</body>
</html>
①<p>...</p>:标签(Tag)。
②p:名称Name成对出现。
③class="title":属性(Attributes)0个或多个。
(2)Beautiful Soup库的引用
Beautiful Soup库,也叫beautifulsoup4或bs4。
from bs4 import BeautifulSoup
或者
import bs4
(3)Beautiful Soup类
HTML文档↔标签树↔BeautifulSoup类。
备注:“↔”表示等价关系。
# Beautiful Soup类
from bs4 import BeautifulSoup
soup = BeautifulSoup('<p>data</p>', 'html.parser')
soup2 = BeautifulSoup(open("H://python//Web Crawler//demo.html"), "html.parser") # 打开一个html文件。
备注:soup2的html文件路径请读者自己配置。
BeautifulSoup对应一个HTML/XML文档的全部内容。
(4)Beautiful Soup库解析器
解析器 | 使用方法 | 条件 |
bs4的HTML解析器 | BeautifulSoup(mk, 'html.parser') | 安装bs4库 |
lxml的HTML解析器 | BeautifulSoup(mk, 'lxml') | pip install lxml |
lxml的XML解析器 | BeautifulSoup(mk, 'xml') | pip install lxml |
html5lib的解析器 | BeautifulSoup(mk, 'html5lib') | pip install html5lib |
(5)Beautiful Soup类的基本元素
基本元素 | 说明 |
Tag | 标签,最基本的信息组织单元,分别用<>和</>标明开头和结尾 |
Name | 标签的名字,<p>...</p>的名字是'p',格式:<tag>.name |
Attributes | 标签的属性,字典形式组织,格式:<tag>.attrs |
NavigableString | 标签内非属性字符串,<>...</>中字符串,格式:<tag>.string |
Comment | 标签内字符串的注释部分,一种特殊的Comment类型 |
回顾demo.html:
演示HTML页面地址:https://python123.io/ws/demo.html。
①标签(Tag):任何存在于HTML语法中的标签都可以用soup.<tag>访问获得,当HTML文档中存在多个相同<tag>对应内容时,soup.<tag>返回第一个。
②标签的名字(Name):每个<tag>都有自己的名字,通过<tag>.name获取,字符串类型。
③标签的属性(Attributes):一个<tag>可以有0或多个属性,字典类型。
④标签内非属性字符串(NavigableString):NavigableString可以跨越多个层次。
⑤标签内字符串的注释部分(Comment):Comment是一种特殊类型。
# Beautiful Soup类的基本元素
# 标签(Tag)
import requests
r = requests.get("http://python123.io/ws/demo.html")
demo = r.text
from bs4 import BeautifulSoup
soup = BeautifulSoup(demo, 'html.parser')
soup.title
print(soup.title)
tag = soup.a
tag
print(tag)
# 标签的名字(Name)
soup.a.name
print(soup.a.name)
soup.a.parent.name
print(soup.a.parent.name)
soup.a.parent.parent.name
print(soup.a.parent.parent.name)
# 标签的属性(Attributes)
tag = soup.a
tag.attrs
print(tag.attrs)
tag.attrs['class']
print(tag.attrs['class'])
tag.attrs['href']
print(tag.attrs['href'])
type(tag.attrs)
print(type(tag.attrs))
type(tag)
print(type(tag))
# 标签内非属性字符串(NavigableString)
soup.a
print(soup.a)
soup.a.string
print(soup.a.string)
soup.p
print(soup.p)
soup.p.string
print(soup.p.string)
type(soup.p.string)
print(type(soup.p.string))
# 标签内字符串的注释部分(Comment)
newsoup = BeautifulSoup("<b><!--This is a comment--></b><p>This is not a comment</p>", "html.parser")
newsoup.b.string
print(newsoup.b.string)
type(newsoup.b.string)
print(type(newsoup.b.string))
newsoup.p.string
print(newsoup.p.string)
type(newsoup.p.string)
print(type(newsoup.p.string))
小结:
<p class="title"> ... </p>
①<p class="title">:标签.<tag>。
②p:名称.Name。
③class="title":属性.attrs。
④...:非属性字符串/注释.string。
3、基于bs4库的HTML内容遍历方法
(1)回顾demo.html
# 回顾demo.html
import requests
r = requests.get("http://python123.io/ws/demo.html")
demo = r.text
(2)HTML基本格式
<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 href="http://www.icourse163.org/course/BIT-268001" class="py1" id="link1">Basic Python</a> and
<a href="http://www.icourse163.org/course/BIT-1001870001" class="py2" id="link2">Advanced Python</a>.
</p>
</body>
</html>
(3)标签树的遍历方式
html或者xml都是树形结构。
三种遍历方式:下行遍历、上行遍历、平行遍历。
BeautifulSoup类型是标签树的根节点。
①标签树的下行遍历:
属性 | 说明 |
.contents | 子节点的列表,将<tag>所有儿子节点存入列表 |
.children | 子节点的迭代类型,与.contents类似,用于循环遍历儿子节点 |
.descendants | 子孙节点的迭代类型,包含所有子孙节点,用于循环遍历 |
# 标签树的下行遍历
soup = BeautifulSoup(demo, 'html.parser')
soup.head
print(soup.head)
soup.head.contents
print(soup.head.contents)
soup.body.contents
print(soup.body.contents)
len(soup.body.contents)
print(len(soup.body.contents))
len(soup.body.contents[1])
print(len(soup.body.contents[1]))
for child in soup.body.children: # 遍历儿子节点。
print(child)
for child in soup.body.descendants: # 遍历子孙节点。
print(child)
②标签树的上行遍历:
属性 | 说明 |
.parent | 节点的父亲标签 |
.parents | 节点先辈标签的迭代类型,用于循环遍历先辈节点 |
# 标签树的上行遍历
soup = BeautifulSoup(demo, 'html.parser')
soup.title.parent
print(soup.title.parent)
soup.html.parent
print(soup.html.parent)
soup.parent
print(soup.parent)
soup = BeautifulSoup(demo, 'html.parser')
for parent in soup.a.parents: # 遍历soup的a标签的先辈标签。
if parent is None:
print(parent)
else:
print(parent.name)
遍历所有先辈节点,包括soup本身,所以要区别判断。
③标签树的平行遍历:
属性 | 说明 |
.next_sibling | 返回按照HTML文本顺序的下一个平行节点标签 |
.previous_sibling | 返回按照HTML文本顺序的上一个平行节点标签 |
.next_siblings | 迭代类型,返回按照HTML文本顺序的后续所有平行结点标签 |
.previous_siblings | 迭代类型,返回按照HTML文本顺序的前续所有平行节点标签 |
平行遍历发生在同一个父节点下的各节点间。
# 标签树的平行遍历
soup = BeautifulSoup(demo, 'html.parser')
soup.a.next_sibling
print(soup.a.next_sibling)
soup.a.next_sibling.next_sibling
print(soup.a.next_sibling.next_sibling)
soup.a.previous_sibling
print(soup.a.previous_sibling)
soup.a.previous_sibling.previous_sibling
print(soup.a.previous_sibling.previous_sibling)
soup.a.parent
print(soup.a.parent)
for sibling in soup.a.next_sibling: # 遍历后续节点。
print(sibling)
for sibling in soup.a.previous_sibling: # 遍历前续节点。
print(sibling)
4、基于bs4库的HTML格式输出
如何能让HTML页面更加友好的显示?
(1)bs4库的prettify()方法
# bs4库的prettify()方法
import requests
r = requests.get("http://python123.io/ws/demo.html")
demo = r.text
from bs4 import BeautifulSoup
soup = BeautifulSoup(demo, 'html.parser')
soup.prettify()
print(soup.prettify())
print(soup.a.prettify())
.prettify()为HTML文本<>及其内容增加更加’\n’,.prettify()可用于标签,方法:<tag>.prettify()。
(2)bs4库的编码
# bs4库的编码
soup = BeautifulSoup("<p>中文</p>", "html.parser")
soup.p.string # 默认使用UTF‐8编码。
print(soup.p.string)
print(soup.p.prettify())
bs4库将任何HTML输入都变成UTF‐8编码,Python 3.x默认支持编码是UTF‐8,解析无障碍。