BeautifulSoup是一个Python库,用于从HTML或XML文件中提取数据。它创建一个解析树,允许你用类似于CSS或jQuery的方式来导航和提取数据。
以下是一些使用BeautifulSoup的基本示例:
- 安装BeautifulSoup库
pip install beautifulsoup4
- 使用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>
"""
soup = BeautifulSoup(html_doc, 'html.parser')
print(soup.prettify())
- 查找特定的HTML元素
# 查找所有的<a>标签
for anchor in soup.find_all('a'):
print(anchor.get('href'))
# 查找所有带有"title"属性的标签
for tag in soup.find_all(True, {'class': 'title'}):
print(tag.name)
# 通过名称查找一个标签
tag = soup.find(id='link1')
print(tag.get('href'))
- 提取特定的数据
# 获取标题
print(soup.title.string)
# 获取所有段落的文字
for paragraph in soup.find_all('p'):
print(paragraph.get_text())
- 使用CSS选择器查找元素
# 首先需要安装beautifulsoup4-inline-xpath
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>
<div 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.</div>
"""
soup = BeautifulSoup(html_doc, 'html.parser')
# 使用CSS选择器查找
print(soup.select('title'))
print(soup.select('.story'))
print(soup.select('#link1'))
这些是BeautifulSoup的基本使用方法,更多高级功能可以查看官方文档。