在进行数据采集(网页爬虫)时,常用的两个强大工具是 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."
四、扩展:延伸应用
-
结合 pandas 将提取的数据保存为 CSV 文件:
pythonimport 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) -
加入时间延迟与代理(防止被封 IP)
pythonimport 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 爬虫开发的入门组合,通过它们可以快速实现网页数据的采集与清洗。