一、bs4的使用
安装:pip3 install Beautifulsoup4
1.bs4遍历文档树
bs4:解析xml格式的模块,从xml中找想要的数据。
html是xml的一种,解析html,使用requests返回的数据,可能是json、html、文件,再使用bs4解析html格式。
用法:
from bs4 import BeautifulSoup
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" id='id_p' xx='xx'>我是帅哥<b>The Dormouse's story <span>xxx</span></b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
# soup = BeautifulSoup(html_doc, 'html.parser')
# 速度比上面快,但是需要安装lxml模块 pip3 install lxml
soup = BeautifulSoup(html_doc, 'lxml')
res = soup.prettify() # 美化
print(res)
# ----------遍历文档树----------
# 1、用法 通过 .
body = soup.body # 直接通过soup对象.标签名,找到标签对象
print(type(body))
print(body.p)
# bs4.element.Tag 标签对象可以继续往下 .
# 2、获取标签的名称
p = soup.p
print(p.name)
# 3、获取标签的属性
p=soup.p
print(p.attrs) # 把p标签所有属性变成字典
print(p.attrs['class']) # class 是列表形式---->因为class有多个
print(p['id']) # 获取属性第二种方式
# 获取第一个a标签的href属性
a=soup.html.body.a['href']
print(a)
# 4、获取标签的内容
# text string strings
# 获取第一个p标签的文本内容
p = soup.p
print(p.text) # 获取p子子孙孙所有的文本内容,拼到一起
print(p.string) # p标签有且只有文本才能取出,如果有子标签,取出空
print(list(p.strings)) # 把子子孙孙的文本内容放到迭代器中

该文介绍了如何使用Python的BeautifulSoup(bs4)库来解析HTML和XML文档,包括安装、遍历文档树、搜索文档树的方法,如通过标签名、属性、正则表达式等进行查找。同时,文章提到了lxml作为更快的解析器以及如何使用CSS选择器和XPath进行更复杂的查找操作。
最低0.47元/天 解锁文章
2222

被折叠的 条评论
为什么被折叠?



