Python编程实战 - Python实用工具与库 - requests 与 BeautifulSoup

在进行数据采集(网页爬虫)时,常用的两个强大工具是 requests (用于网络请求)和 BeautifulSoup(用于网页解析)。本节我们将学习如何使用这两个库高效地从网页获取并提取数据。


一、requests 库:网络请求的利器

1. requests 简介

requests 是 Python 最常用的 HTTP 请求库,用于发送各种网络请求(GET、POST、PUT、DELETE 等)。相比内置的 urllib,它更加简单易用。

安装:

bash 复制代码
pip install requests

2. 发送请求

python 复制代码
import requests

# 发送 GET 请求
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")

# 打印响应内容
print(response.status_code)  # 状态码,如 200 表示成功
print(response.text)         # 响应的文本内容
print(response.json())       # 如果是 JSON 数据,可直接转成字典

3. 发送 POST 请求

python 复制代码
data = {"title": "Python", "body": "requests demo", "userId": 1}
response = requests.post("https://jsonplaceholder.typicode.com/posts", json=data)
print(response.json())

4. 自定义请求头与参数

python 复制代码
headers = {"User-Agent": "Mozilla/5.0"}
params = {"q": "python"}
response = requests.get("https://www.google.com/search", headers=headers, params=params)
print(response.url)

5. 处理异常

python 复制代码
try:
    response = requests.get("https://example.com", timeout=5)
    response.raise_for_status()  # 检查响应是否为 200
except requests.RequestException as e:
    print("请求出错:", e)

二、BeautifulSoup:HTML 解析神器

1. BeautifulSoup 简介

BeautifulSoup 是一个强大的 HTML/XML 解析库,可以轻松提取网页中的指定数据。

安装:

bash 复制代码
pip install beautifulsoup4 lxml

2. 基本使用

python 复制代码
from bs4 import BeautifulSoup

html = """
<html><head><title>Python 教程</title></head>
<body><h1>欢迎学习 BeautifulSoup</h1><p class='desc'>这是一个爬虫示例</p></body></html>
"""

soup = BeautifulSoup(html, "lxml")
print(soup.title.text)   # 输出:Python 教程
print(soup.h1.text)      # 输出:欢迎学习 BeautifulSoup
print(soup.find("p", class_="desc").text)  # 输出:这是一个爬虫示例

3. 常见的解析方法

python 复制代码
# 查找第一个匹配的标签
print(soup.find("p"))

# 查找所有匹配的标签
for p in soup.find_all("p"):
    print(p.text)

# 使用 CSS 选择器
print(soup.select_one("p.desc").text)
print([a.text for a in soup.select("a.link")])

三、requests + BeautifulSoup 实战示例:爬取网页标题

python 复制代码
import requests
from bs4 import BeautifulSoup

url = "https://quotes.toscrape.com/"
headers = {"User-Agent": "Mozilla/5.0"}

response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, "lxml")

quotes = soup.find_all("span", class_="text")
authors = soup.find_all("small", class_="author")

for quote, author in zip(quotes, authors):
    print(f"{author.text}: {quote.text}")

运行结果(示例):

dart 复制代码
Albert Einstein: "The world as we have created it is a process of our thinking."
J.K. Rowling: "It is our choices that show what we truly are, far more than our abilities."

四、扩展:延伸应用

  1. 结合 pandas 将提取的数据保存为 CSV 文件:

    python 复制代码
    import pandas as pd
    df = pd.DataFrame({"author": [a.text for a in authors], "quote": [q.text for q in quotes]})
    df.to_csv("quotes.csv", index=False)
  2. 加入时间延迟与代理(防止被封 IP)

    python 复制代码
    import time
    import random
    time.sleep(random.uniform(1, 3))

总结

模块 功能 常用方法
requests 发送 HTTP 请求 get(), post(), headers, params, json()
BeautifulSoup 解析 HTML/XML 文档 find(), find_all(), select(), .text

这两个库是 Python 爬虫开发的入门组合,通过它们可以快速实现网页数据的采集与清洗。


相关推荐
源码之家9 分钟前
大数据毕业设计汽车推荐系统 Django框架 可视化 协同过滤算法 数据分析 大数据 机器学习(建议收藏)✅
大数据·python·算法·django·汽车·课程设计·美食
GreatSQL9 分钟前
一文搞懂 MySQL/GreateSQL 只读参数:read_only 参数核心区别
后端
HealthScience10 分钟前
COM Surrogate的dllhost.exe高占用(磁盘)解决
python
羊小猪~~13 分钟前
【QT】-- 模型与视图简介
开发语言·数据库·c++·后端·qt·前端框架·个人开发
站大爷IP14 分钟前
用 Python 30 分钟做出自己的记事本
python
曲幽14 分钟前
FastAPI里玩转Redis和数据库的正确姿势,别让异步任务把你坑哭了!
redis·python·mysql·fastapi·web·celery·sqlalchemy·task·backgroundtask
二十一_15 分钟前
炸了!Claude Code 51万行源码全部泄露,我已经拿到了完整代码
前端·langchain·claude
RePeaT20 分钟前
npm 依赖版本号中 `^` 和 `~` 到底有什么区别?
前端·javascript·npm
未知鱼21 分钟前
Python安全开发之简易csrf检测工具
python·安全·csrf
古法安卓22 分钟前
Android-NTP时间同步机制
后端