简介

  • python3 bs4模块相关笔记

python3 bs4模块 详解

BeautifulSoup 是一个用于从HTML和XML文档中提取数据的Python库。它为用户提供了简单的API,使得解析、导航和搜索文档树变得更加直观和高效。以下是BeautifulSoup库的一些关键概念和使用方法的详细介绍。

1. 安装

首先,你需要安装 BeautifulSoup4 以及一个解析器库(例如 lxmlhtml.parser)。

1
pip install beautifulsoup4 lxml

2. 基本使用

导入模块并创建 BeautifulSoup 对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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>
</body>
</html>
"""

soup = BeautifulSoup(html_doc, 'lxml')  # 使用 lxml 解析器

3. 基本导航

BeautifulSoup 提供了多种方式来导航和操作文档树。

3.1 标签选择

你可以使用标签名直接选择标签。

1
2
3
print(soup.title)  # <title>The Dormouse's story</title>
print(soup.title.name)  # title
print(soup.title.string)  # The Dormouse's story

3.2 获取标签的属性

标签的属性可以当作字典来访问。

1
2
3
print(soup.a)  # <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>
print(soup.a['href'])  # http://example.com/elsie
print(soup.a['class'])  # ['sister']

3.3 直接子节点和所有子节点

contents 属性可以返回直接子节点列表,children 可以用于遍历直接子节点,而 descendants 则会递归遍历所有子节点。

1
2
3
4
5
6
print(soup.body.contents)  # 直接子节点
for child in soup.body.children:
    print(child)

for descendant in soup.body.descendants:
    print(descendant)

4. 搜索文档树

BeautifulSoup 提供了几种查找文档树中特定元素的方法。

4.1 find_all()

查找所有符合条件的元素。

1
2
3
links = soup.find_all('a')
for link in links:
    print(link['href'])

4.2 find()

查找第一个符合条件的元素。

1
2
first_link = soup.find('a')
print(first_link['href'])  # http://example.com/elsie

4.3 使用 CSS 选择器

你可以使用 .select() 方法通过CSS选择器语法查找元素。

1
print(soup.select('p.title'))  # 选择类名为 title 的 <p> 标签

5. 修改文档树

BeautifulSoup 允许你直接修改文档内容。

5.1 修改标签内容

你可以直接修改标签的 .string 属性来更改其内容。

1
2
soup.title.string = "New Title"
print(soup.title)  # <title>New Title</title>

5.2 插入和删除标签

你可以使用 append()insert()decompose() 等方法来添加或删除标签。

1
2
3
4
5
new_tag = soup.new_tag("p")
new_tag.string = "This is a new paragraph."
soup.body.append(new_tag)  # 添加新标签到 body

soup.p.decompose()  # 删除第一个 <p> 标签

6. 输出修饰后的HTML

修改完文档树后,你可以使用 prettify() 方法以缩进格式输出HTML。

1
print(soup.prettify())

7. 使用示例

一个简单的例子,展示如何提取所有链接,并打印它们的文本和链接地址:

1
2
for link in soup.find_all('a'):
    print(f"Text: {link.string}, URL: {link['href']}")

8. 处理复杂的HTML

BeautifulSoup 可以非常有效地处理和解析有错误或不完整的HTML。它会自动修复文档树,使其更易于解析。


这就是 BeautifulSoup 库的基本使用方法和主要功能。通过这些方法,你可以轻松地从复杂的HTML文档中提取所需的信息。