from bs4 import BeautifulSoup
# 自定义网页进行过滤
html = """
<html>
<title>this is a test website</title>
<body>
<p id='fruit' class='myfavourite'>i like eating apple</p>
<p id='fruit'>i like eating peach too</p>
<p id='website'>i have my personal website </p>
<p id='country'>i am chinese</p>
<p> id='session 'i like summer</p>
<h1 class="favourite runnning">i like playing football</h1>
<td>
<tr>i am a boy</tr>
<tr>i am 17 years old</tr>
</td>
<body>
</html>
"""
# 建立beautifulsoup4 对象,设定解析器为 lxml
bs = BeautifulSoup(html,"lxml")
# 将 html 格式化后以Unicode编码输出,每个XML/HTML标签都独占一行。
print(bs.prettify())
print("我是分隔符===============================================")
# 打印第一个 tag 为 title 的标签
print(bs.title)
# 打印第一个 tag 为 title 的标签名字
print(bs.title.name)
# 打印第一个 p 标签的属性
print(bs.p.attrs)
# 打印第一个 p 标签 id 属性的值
print(bs.p.attrs['id'])
# 打印第一个 tag 为 title 中的文字
print(bs.title.string)
# 打印第一个 tag 为 title 的 父标签的 名字
print(bs.title.parent.name)
# 在bs4 中最大的标签是 [document],在html 上面的是[document] 标签
print(bs.html.parent.name)
# 打印第一个匹配到 attrs={xxx} 的标签
print(bs.find(attrs={'id':'fruit',"class":"myfavourite"}))
# 搜索所有匹配的标签,返回一个列表
print(bs.find_all(id='fruit'))
beautifulsoup4 练习
最新推荐文章于 2022-06-21 11:02:00 发布