📜  beautifulsoup 用法 (1)

📅  最后修改于: 2023-12-03 15:29:36.581000             🧑  作者: Mango

Beautiful Soup 用法

简介

Beautiful Soup 是一个 Python 的第三方库,用于解析 HTML 和 XML 文件,可以方便地从这些文件中提取需要的信息。它提供了一些简单而又强大的工具,使得解析复杂的 HTML 和 XML 文件变得更加容易。

安装

通过 pip 安装:

pip install beautifulsoup4
使用
1. 解析 HTML

Beautiful Soup 提供了多种方式来解析 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')

# 解析文件
with open('index.html') as fp:
    soup = BeautifulSoup(fp, 'html.parser')
2. 搜索文档树

Beautiful Soup 提供了多种搜索文档树的方法,常用的两种方法是 find() 和 find_all()。

# 使用 find()
soup.find('a')
soup.find('a', href='http://example.com/elsie')

# 使用 find_all()
soup.find_all('a')
soup.find_all('a', class_='sister')
3. 访问节点信息

Beautiful Soup 支持直接访问 HTML 标签的名字、属性、内容等信息。

# 获取标签名
soup.title.name

# 获取标签的属性
soup.a['href']

# 获取标签内容
soup.title.string
4. 修改节点信息

Beautiful Soup 支持修改 HTML 标签的名字、属性、内容等信息。

# 修改标签名
soup.title.name = 'mytitle'

# 修改标签属性
soup.a['href'] = 'http://example.com/'

# 修改标签内容
soup.title.string = 'New title'
总结

Beautiful Soup 是一个功能强大的 HTML 和 XML 解析库,提供了多种搜索文档树和访问节点信息的方法,方便地从 HTML 和 XML 文件中提取需要的信息,并能够修改节点信息。