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


相关推荐
颜酱43 分钟前
图结构完全解析:从基础概念到遍历实现
javascript·后端·算法
喵手1 小时前
Python爬虫实战:旅游数据采集实战 - 携程&去哪儿酒店机票价格监控完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集结果csv导出·旅游数据采集·携程/去哪儿酒店机票价格监控
2501_944934731 小时前
高职大数据技术专业,CDA和Python认证优先考哪个?
大数据·开发语言·python
helloworldandy1 小时前
使用Pandas进行数据分析:从数据清洗到可视化
jvm·数据库·python
失忆爆表症1 小时前
05_UI 组件库集成指南:Shadcn/ui + Tailwind CSS v4
前端·css·ui
小迷糊的学习记录1 小时前
Vuex 与 pinia
前端·javascript·vue.js
发现一只大呆瓜2 小时前
前端性能优化:图片懒加载的三种手写方案
前端·javascript·面试
不爱吃糖的程序媛2 小时前
Flutter 与 OpenHarmony 通信:Flutter Channel 使用指南
前端·javascript·flutter
利刃大大2 小时前
【Vue】Element-Plus快速入门 && Form && Card && Table && Tree && Dialog && Menu
前端·javascript·vue.js·element-plus
NEXT062 小时前
AI 应用工程化实战:使用 LangChain.js 编排 DeepSeek 复杂工作流
前端·javascript·langchain