(四)Beautiful Soup库入门
BeautifulSoup库官方文档
(1) Beautiful Soup库基本元素
<p class="title">...</p>
<p>..</p> :标签 Tag
p :名称 Name (成对出现)
class='title':属性 Attributes (0个或多个)
from bs4 import BeautifulSoup
soup1 = BeautifulSoup("<html>data</html>","html.parser")
soup2 = BeautifulSoup("open("D://demo.html")","html.parser")
(2) BeautifulSoup库解析器
解析器 |
使用方法 |
条件 |
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 |
(3) BeautifulSoup类的基本元素
例:<p class="title">...</p>
基本元素 |
说明 |
Tag |
标签,最基本的信息组织单元,用<>和</>标记开头和结尾 |
Name |
标签的名字, …
的名字是’p’,格式:.name |
Attributes |
标签的属性,字典形式组织,格式:.attrs |
NavigableString |
标签内非属性字符串,<>…</>中字符串,格式:.string |
Comment |
标签内字符串的注释部分,一种特殊的Comment类型 |
from bs4 import BeautifulSoup
soup = BeautifulSoup(demo,"html.parser")
soup.title
soup.a
soup.find_all('a')
soup.get_text()
soup.a.name
soup.a.parent.name
soup.a.parent.parent.name
tag.attrs
tag.attrs['class']
soup.a.string
newsoup = BeautifulSoup("<b><!--This is a comment--></b><p>This is not a comment</p>","html.parser")
newsoup.b.string
newsoup.p.string
(4) 基于bs4库的HTML内容遍历方法
1.标签树的下行遍历
属性 |
说明 |
.contents |
子节点的列表,将所有儿子节点存入列表 |
.children |
子节点的迭代类型,与.contents类似,用于循环遍历儿子节点 |
.descendants |
子孙节点的迭代类型,包含所有子孙节点,用于循环遍历 |
soup = BeautifulSoup(demo, "html.parser")
soup.head
soup.head.contents
soup.body.contents
len(soup.body.contents)
soup.body.contents[1]
for child in soup.body.children:
print(child)
for child in soup.body.descendants:
print(children)
2.标签树的上行遍历
属性 |
说明 |
.parent |
节点的父亲标签 |
.parents |
节点先辈标签的迭代类型,用于循环遍历先辈节点 |
soup = BeautifulSoup(demo, "html.parser")
for parent in soup.a.parents:
if parent is None:
print(parent)
else:
print(parent.name)
3.标签树的平行遍历
属性 |
说明 |
.next_sibling |
返回按照HTML文本顺序的下一个平行节点标签 |
.previous_sibling |
返回按照HTML文本顺序的上一个平行节点标签 |
.next_siblings |
迭代类型,返回按照HTML文本顺序的后续平行节点标签 |
.previous_siblings |
迭代类型,返回按照HTML文本顺序的前续平行节点标签 |
for sibling in soup.a.next_sibling:
print(sibling)
for sibling in soup.a.previous_sibling:
print(sibling)
(5) 基于bs4库的HTML格式输出
soup.prettify()
soup.a.prettify()
节点标签 |
| .previous_sibling | 返回按照HTML文本顺序的上一个平行节点标签 |
| .next_siblings | 迭代类型,返回按照HTML文本顺序的后续平行节点标签 |
| .previous_siblings | 迭代类型,返回按照HTML文本顺序的前续平行节点标签 |
[外链图片转存中…(img-mxfhEfda-1586863050051)]
for sibling in soup.a.next_sibling:
print(sibling)
for sibling in soup.a.previous_sibling:
print(sibling)
(5) 基于bs4库的HTML格式输出
soup.prettify()
soup.a.prettify()