Python BeautifulSoup 提取 HTML 超链接教程
您可以使用Python的BeautifulSoup库来解析HTML并提取超链接。下面是一个示例代码:
from bs4 import BeautifulSoup
# 假设您已经获取了一段HTML并将其存储在变量html中
html = """<html>
<body>
<h1>网页标题</h1>
<ul>
<li><a href="http://www.example.com">链接1</a></li>
<li><a href="http://www.example.com/page2">链接2</a></li>
<li><a href="http://www.example.com/page3">链接3</a></li>
</ul>
</body>
</html>"""
# 使用BeautifulSoup解析HTML
soup = BeautifulSoup(html, 'html.parser')
# 查找所有超链接
links = soup.find_all('a')
# 遍历超链接并打印
for link in links:
href = link['href']
text = link.text
print(f"超链接文本:{text},超链接地址:{href}")
这段代码会输出每个超链接的文本和地址:
超链接文本:链接1,超链接地址:http://www.example.com
超链接文本:链接2,超链接地址:http://www.example.com/page2
超链接文本:链接3,超链接地址:http://www.example.com/page3
您可以根据需要进一步处理这些超链接,例如提取特定域名的链接或执行其他操作。
原文地址: https://www.cveoy.top/t/topic/qxad 著作权归作者所有。请勿转载和采集!