温馨提示×

Python中怎么安装BeautifulSoup

小亿
82
2024-05-14 13:36:21
栏目: 编程语言

在 Python 中安装 BeautifulSoup 库,您可以使用 pip 工具

pip install beautifulsoup4

这将安装 BeautifulSoup 4 的最新版本。安装完成后,您可以在 Python 代码中导入 BeautifulSoup 库并使用它。

以下是一个简单的示例,展示了如何使用 BeautifulSoup 解析 HTML 文档:

from bs4 import BeautifulSoup

html_doc = """
<html><head<title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</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')

# 打印标题
print(soup.title.string)

# 打印所有链接
for link in soup.find_all('a'):
    print(link.get('href'))

在这个示例中,我们首先导入 BeautifulSoup 库,然后使用 BeautifulSoup 类解析 HTML 文档。接下来,我们使用 soup.title.string 获取标题,使用 soup.find_all('a') 查找所有的链接,并使用 link.get('href') 获取链接的 href 属性。

请注意,要使用 BeautifulSoup,您需要先安装它。在安装 BeautifulSoup 之前,请确保已经安装了 Python 和 pip

0