beautifulsoup4

beautifulsoup4,通常简称为 BeautifulSoup,是一个用于解析HTML和XML文档的Python库。它提供了一个简单易用的接口和丰富的解析库,可以用于网页抓取(web scraping)和数据分析等任务。BeautifulSoup 与 Python 的内置 HTML 解析器以及第三方解析器如 lxmlhtml5lib 一起工作。 以下是 BeautifulSoup 的一些关键特点和用法:

关键特点

  1. 解析器兼容性:支持多种解析器,包括 Python 标准库中的 html.parser,以及第三方库 lxmlhtml5lib
  2. 易于使用:提供了简洁的API,使得提取HTML文档中的数据变得简单。
  3. 强大的选择器:可以使用多种方式定位和提取元素,如标签名、属性、CSS类等。
  4. 容错性:能够很好地处理不规范的HTML和XML文档。
  5. 转换方法:可以将解析树转换成字符串,或者将文档转换成JSON格式。

安装

可以通过pip安装beautifulsoup4

pip install beautifulsoup4

如果需要使用 lxmlhtml5lib 作为解析器,也需要安装这些库:

pip install lxml
pip install html5lib

基本用法

以下是一个使用 BeautifulSoup 的基本示例:

from bs4 import BeautifulSoup
# 示例HTML文档
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>
"""
# 使用BeautifulSoup解析文档
soup = BeautifulSoup(html_doc, 'html.parser')
# 打印标题
print(soup.title.string)
# 找到所有<a>标签的链接
for link in soup.find_all('a'):
    print(link.get('href'))

常用方法

使用场景