BeautifulSoup 是一个 Python 库,用于解析 HTML 和 XML 文档。它通过解析 HTML 或 XML 文档,并将其转换为一个复杂的树形结构,然后可以通过这个树形结构方便地获取任何信息。

快速开始

以下是 BeautifulSoup 的基本用法:

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.prettify())

标签和属性

BeautifulSoup 通过标签和属性来定位 HTML 元素。

标签

print(soup.title.name)  # 输出: title
print(soup.title.string)  # 输出: The Dormouse's story

属性

print(soup.a['href'])  # 输出: http://example.com/elsie

选择器

BeautifulSoup 提供了多种选择器,用于查找特定的 HTML 元素。

类选择器

print(soup.find_all('a', class_='sister'))  # 查找所有类名为 sister 的 a 标签

ID 选择器

print(soup.find(id='link1')['href'])  # 查找 ID 为 link1 的 a 标签的 href 属性

图片

print(soup.find('img')['src'])  # 查找第一个 img 标签的 src 属性

下一站

如果你想要更深入地了解 BeautifulSoup,可以阅读 官方文档

[

HTMLParser
]

[

BeautifulSoup
]

[

HTML
]