以下是使用BeautifulSoup库从HTML文档中提取数据的示例代码:
import requests
from bs4 import BeautifulSoup
# 发送请求并获取HTML文档
url = "https://example.com"
response = requests.get(url)
html_doc = response.text
# 使用BeautifulSoup解析HTML文档
soup = BeautifulSoup(html_doc, 'html.parser')
# 提取特定的数据
title = soup.title.string
print("网页标题:", title)
# 查找所有的链接
links = soup.find_all('a')
for link in links:
print("链接文本:", link.text)
print("链接地址:", link['href'])
在上面的示例代码中,我们首先使用requests库发送请求并获取HTML文档。然后,我们使用BeautifulSoup库将HTML文档解析为一个BeautifulSoup对象。接下来,我们可以使用BeautifulSoup对象来提取特定的数据。
在示例中,我们首先提取并打印了网页的标题。然后,我们使用find_all方法查找所有的a标签,并遍历打印每个链接的文本和地址。
请注意,要运行此示例,您需要先安装BeautifulSoup库和requests库。您可以使用以下命令安装它们:
pip install bs4
pip install requests
上一篇:BeautifulSoup试图从包装的div中获取文本,但返回的结果要么为空,要么为“none”。
下一篇:BeautifulSoup使用replace方法删除标签时出错'NoneType'objectisnotcallable。