文章目录
使用BeautifulSoup查找具有给定属性值的标签
在本文中,我们将讨论如何使用 beautifulsoup 在 HTML 文档中查找具有给定属性值的标签。
语法如下:
Syntax: find(attr_name=”value”)
BeautifulSoup查找给定属性值标签方法
- 导入模块。
- 从网页中抓取数据。
- 将抓取的字符串解析为 HTML。
- 使用 find() 函数查找属性和标签。
- 打印结果。
1、示例

# importing module
from bs4 import BeautifulSoup
markup = '''<html><body><div id="container">Div Content</div></body></html>'''
soup = BeautifulSoup(markup, 'html.parser')
# finding the tag with the id attribute
div_bs4 = soup.find(id = "container")
print(div_bs4.name)
输出:
div
2、示例

# importing module
from bs4 import BeautifulSoup
markup = '''<html><body><a href="https://www.geeksforgeeks.org/">Geeks for Geeks</a></body></html>'''
soup = BeautifulSoup(markup, 'html.parser')
# finding the tag with the href attribute
div_bs4 = soup.find(href = "https://www.geeksforgeeks.org/")
print(div_bs4.name)
输出:
a
3、示例

# importing module
from bs4 import BeautifulSoup
markup = """<html><head><title>Welcome to geeksforgeeks</title></head>
<body>
<p class="title"><b>Geeks</b></p>
<p class="gfg">geeksforgeeks a computer science portal for geeks
</body>
"""
soup = BeautifulSoup(markup, 'html.parser')
# finding the tag with the class attribute
div_bs4 = soup.find(class_ = "gfg")
print(div_bs4.name)
输出:
p