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 爬虫开发的入门组合,通过它们可以快速实现网页数据的采集与清洗。


相关推荐
Together_CZ9 分钟前
DarkIR: Robust Low-Light Image Restoration——鲁棒的低光照图像复原
python·image·robust·darkir·鲁棒的低光照图像复原·low-light·restoration
shoubepatien20 分钟前
JAVA -- 12
java·后端·intellij-idea
拾贰_C23 分钟前
【python | pytorch | scipy】scipy scikit-learn库相互依赖?
pytorch·python·scipy
木木一直在哭泣29 分钟前
Spring 里的过滤器(Filter)和拦截器(Interceptor)到底啥区别?
后端
码农秋30 分钟前
Element Plus DatePicker 日期少一天问题:时区解析陷阱与解决方案
前端·vue.js·elementui·dayjs
BoBoZz1930 分钟前
PolyDataContourToImageData 3D集合图像转换成等效3D二值图像
python·vtk·图形渲染·图形处理
未来之窗软件服务34 分钟前
未来之窗昭和仙君(五十六)页面_预览模式——东方仙盟筑基期
前端·仙盟创梦ide·东方仙盟·昭和仙君·东方仙盟架构
2401_8414956434 分钟前
【自然语言处理】关系性形容词的特征
人工智能·python·自然语言处理·自动识别·特征验证·关系性形容词·语言学规则和计算
top_designer36 分钟前
Illustrato:钢笔工具“退休”了?Text to Vector 零基础矢量生成流
前端·ui·aigc·交互·ux·设计师·平面设计
源码获取_wx:Fegn089537 分钟前
基于springboot + vue物业管理系统
java·开发语言·vue.js·spring boot·后端·spring·课程设计