解析库bs4的使用

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

一、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))  # 把子子孙孙的文本内容放到迭代器中

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

妍婧

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值