BeautifulSoup

简介: 【8月更文挑战第17天】

BeautifulSoup 是一个用于解析 HTML 和 XML 文档的 Python 库。它能够从网页中提取数据,而且由于其易用性,BeautifulSoup 常被用于网络爬虫中。以下是 BeautifulSoup 的基本使用方法和一些代码示例。

安装 BeautifulSoup

首先,你需要安装 BeautifulSoup 库,以及一个解析器库,如 lxmlhtml.parser。通常 lxml 更快,但 html.parser 是 Python 内置的,不需要额外安装。

pip install beautifulsoup4
pip install lxml  # 或者 pip install html5lib

BeautifulSoup 基本用法

代码示例(解析 HTML):

from bs4 import BeautifulSoup

# 假设我们有一段 HTML 内容
html_doc = "<html><head><title>The Dormouse's story</title></head><body>"
html_doc += "<p class='title'><b>The Dormouse's story</b></p>"
html_doc += "<p class='story'>Once upon a time there were three little sisters</p></body></html>"

# 创建一个 BeautifulSoup 对象,第二个参数是解析器名称
soup = BeautifulSoup(html_doc, 'html.parser')

# 获取标题
print(soup.title.string)

# 通过标签名获取所有段落
paragraphs = soup.find_all('p')
for p in paragraphs:
    print(p.text)

# 使用 CSS 选择器
print(soup.select_one('p.title > b').text)

提取数据

代码示例(提取链接):

from bs4 import BeautifulSoup

# 假设我们从网页获取了 HTML 内容
html = '<html><head></head><body><a href="http://example.com">Example</a></body></html>'

soup = BeautifulSoup(html, 'html.parser')

# 提取所有链接的 URL
for link in soup.find_all('a'):
    print(link['href'])

处理嵌套数据

代码示例(提取表格数据):

from bs4 import BeautifulSoup

html = """
<table>
    <tr>
        <th>Month</th>
        <th>Savings</th>
    </tr>
    <tr>
        <td>January</td>
        <td>$100</td>
    </tr>
    <!-- 更多行 -->
</table>
"""

soup = BeautifulSoup(html, 'html.parser')

table = soup.find('table')
rows = table.find_all('tr')

for row in rows:
    cells = row.find_all('td')
    print([cell.text for cell in cells])

与 Requests 库结合使用

代码示例(从网页抓取数据):

import requests
from bs4 import BeautifulSoup

# 发送 HTTP 请求
response = requests.get('http://example.com')

# 解析响应内容
soup = BeautifulSoup(response.text, 'html.parser')

# 提取数据
print(soup.title.text)

异常处理

在使用 BeautifulSoup 时,也可能会遇到一些异常情况,如找不到标签或属性。使用 try-except 语句可以处理这些异常。

代码示例(异常处理):

from bs4 import BeautifulSoup

soup = BeautifulSoup("<tag>no attributes</tag>", 'html.parser')

try:
    # 尝试获取不存在的属性
    print(soup.tag['nonexistent'])
except KeyError as e:
    print(f"Attribute not found: {e}")

`

目录
相关文章
|
缓存 固态存储 关系型数据库
MySQL性能优化指南:深入分析重做日志刷新到磁盘的机制
MySQL性能优化指南:深入分析重做日志刷新到磁盘的机制
751 0
|
4月前
|
机器学习/深度学习 算法 调度
基于遗传算法GA算法优化BP神经网络(Python代码实现)
基于遗传算法GA算法优化BP神经网络(Python代码实现)
286 0
|
算法 网络协议 物联网
|
数据采集 网络协议 Java
HTTP调用:你考虑到超时、重试、并发了吗?
今天,我们一起聊聊进行 HTTP 调用需要注意的超时、重试、并发等问题。
602 0
|
SQL 数据挖掘 BI
【超实用技巧】解锁SQL聚合函数的奥秘:从基础COUNT到高级多表分析,带你轻松玩转数据统计与挖掘的全过程!
【8月更文挑战第31天】SQL聚合函数是进行数据统计分析的强大工具,可轻松计算平均值、求和及查找极值等。本文通过具体示例,展示如何利用这些函数对`sales`表进行统计分析,包括使用`COUNT()`、`SUM()`、`AVG()`、`MIN()`、`MAX()`等函数,并结合`GROUP BY`和`HAVING`子句实现更复杂的数据挖掘需求。通过这些实践,你将学会如何高效地应用SQL聚合函数解决实际问题。
292 0
|
调度
【机会约束、鲁棒优化】机会约束和鲁棒优化研究优化【ccDCOPF】研究(Matlab代码实现)
【机会约束、鲁棒优化】机会约束和鲁棒优化研究优化【ccDCOPF】研究(Matlab代码实现)
340 0
|
存储 安全 Java
深入理解Java字节码与反编译技术
深入理解Java字节码与反编译技术
310 0
|
存储 Linux Apache
容器的文件系统挂载
本实验介绍了容器中文件和文件夹的挂载和使用
|
前端开发 定位技术
QT使用QML实现地图绘制虚线
QML提供了MapPolyline用于在地图上绘制线段,该线段是实线,因此我使用Canvas自定义绘制的方式在地图上绘制线段
338 0
|
数据采集 Python
利用Python通过商品条形码查询商品信息
利用Python通过商品条形码查询商品信息
866 0