BeautifulSoup 是一个 Python 库,用于从 HTML 或 XML 文件中提取数据。它创建了一个解析树,方便地提取标签和数据。由于其易用性和强大的功能,BeautifulSoup 常与 urllib 或 requests 库一起使用,用于网络爬虫项目。
以下是 BeautifulSoup 的一些关键特性:
- 能够解析大多数的糟糕标记的 HTML。
- 提供了简单易用的 API 来提取标签和数据。
- 可以与
Python标准库中的 HTML 解析器一起使用,如html.parser。 - 也可以与第三方解析器一起使用,如
lxml和html5lib。
要使用 BeautifulSoup,你需要先安装它,通常使用 pip:
pip install beautifulsoup4
以下是一些使用 BeautifulSoup 的推荐代码示例:
基本用法:
from bs4 import BeautifulSoup import requests url = 'http://www.example.com' response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') print(soup.prettify()) # 打印格式化的HTML提取标签:
# 提取所有<a>标签 a_tags = soup.find_all('a') for tag in a_tags: print(tag.get('href')) # 打印链接使用 CSS 选择器:
如果你使用的是lxml作为解析器,BeautifulSoup还支持 CSS 选择器:soup.select('a[href^="http://"]') # 选择所有以http://开头的<a>标签的href属性提取属性:
img_tags = soup.find_all('img') for img in img_tags: print(img.get('src')) # 打印图片的src属性文本提取:
# 提取并打印<p>标签中的文本 p_tags = soup.find_all('p') for p in p_tags: print(p.get_text())嵌套标签提取:
# 提取<div>标签内的所有<p>标签 div = soup.find('div', class_='some-class') p_tags = div.find_all('p') for p in p_tags: print(p.get_text())使用
lxml解析器:lxml是一个快速的解析器,可以提高BeautifulSoup的解析速度:from bs4 import BeautifulSoup with open('index.html', 'r') as file: soup = BeautifulSoup(file, 'lxml')