很多人听到“爬虫”两个字就觉得高深莫测:什么反爬、js 渲染、ip 封禁……其实,80% 的公开数据采集需求,只用 requests 就能解决。
本文不讲花活,只讲一件事:如何用 requests 把网页上的数据“搬”下来,并把它变成你能用的结构化数据。
一、什么是 requests?为什么它适合入门?
requests 是 python 中最常用的 http 请求库,可以理解为:
用代码模拟浏览器访问网页
它的优点非常明显:
- ✅ api 简洁,像说人话一样写代码
- ✅ 不需要配置复杂的浏览器环境
- ✅ 适合抓静态网页(服务器直接返回 html)
- ✅ 学习成本低,10 分钟上手
一句话:requests 是爬虫世界的“hello world”。
二、环境准备
1. 安装 requests
pip install requests
(如果你用的是 anaconda,通常已内置)
2. 必备辅助库(后面会用到)
pip install beautifulsoup4 lxml
beautifulsoup4:解析 htmllxml:高性能解析器
三、第一个爬虫:抓取一个网页
1. 发送 get 请求
import requests url = "https://example.com" response = requests.get(url) print(response.status_code) # 200 表示成功 print(response.text[:500]) # 查看前 500 个字符
2. 常见状态码速查
状态码 | 含义 |
|---|---|
200 | 成功 |
403 | 被拒绝(可能反爬) |
404 | 页面不存在 |
500 | 服务器错误 |
四、伪装成浏览器(非常重要)
很多网站会拒绝“非浏览器”的请求。解决办法很简单:加一个 user-agent。
headers = {
"user-agent": "mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36"
}
response = requests.get(url, headers=headers)这是爬虫的第一条军规:永远带上 headers
五、解析网页:从 html 中提取数据
拿到 html 只是第一步,我们需要从中“抠”出想要的内容。
1. beautifulsoup 初体验
from bs4 import beautifulsoup soup = beautifulsoup(response.text, "lxml") title = soup.title.text print(title)
2. 提取标签内容
查找单个元素
h1 = soup.find("h1").text查找多个元素
links = soup.find_all("a")
for link in links:
print(link.get("href"), link.text)3. 使用 css 选择器(强烈推荐)
# 提取 class="price" 的元素
prices = soup.select(".price")
# 提取 ul 下的 li
items = soup.select("ul.items > li")css 选择器和你在浏览器开发者工具里看到的一致,非常好用
六、实战案例:抓取豆瓣读书 top 250(示例)
仅作学习用途,遵守网站 robots.txt 与访问频率限制
import requests
from bs4 import beautifulsoup
url = "https://book.douban.com/top250"
headers = {
"user-agent": "mozilla/5.0"
}
resp = requests.get(url, headers=headers)
soup = beautifulsoup(resp.text, "lxml")
books = soup.select(".item .pl2 a")
for book in books:
title = book.text.strip().replace("\n", "")
link = book["href"]
print(title, link)运行后,你将得到一份干净的图书清单。
七、参数化请求:翻页与搜索
1. url 参数(get 参数)
params = {
"q": "python",
"page": 2
}
response = requests.get(
"https://www.example.com/search",
params=params,
headers=headers
)
print(response.url)
# https://www.example.com/search?q=python&page=2不用自己拼 url,requests 帮你搞定
2. 简单翻页爬虫模板
for page in range(1, 6):
url = f"https://example.com/list?page={page}"
resp = requests.get(url, headers=headers)
# 解析数据八、异常处理:让爬虫更健壮
1. 捕获请求异常
try:
resp = requests.get(url, headers=headers, timeout=5)
resp.raise_for_status()
except requests.exceptions.requestexception as e:
print("请求失败:", e)2. 常用参数
requests.get(
url,
headers=headers,
timeout=5, # 超时时间
verify=false # 忽略 ssl 证书(慎用)
)九、数据存储:别只打印不保存
1. 保存为 csv(最常用)
import csv
with open("data.csv", "w", newline="", encoding="utf-8-sig") as f:
writer = csv.writer(f)
writer.writerow(["标题", "链接"])
writer.writerow([title, link])2. 保存为 json
import json
data = [{"title": title, "link": link}]
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=false, indent=2)十、爬虫礼仪(非常重要)
✅ 合法合规
- 不抓取隐私数据
- 遵守网站
robots.txt - 不用于商业用途(除非授权)
✅ 减轻服务器压力
- 控制请求频率(
time.sleep(1)) - 不在高峰期疯狂爬取
import time time.sleep(1)
✅ 标识自己
- 有些网站允许爬虫,建议在 user-agent 中写明联系方式
十一、requests 的局限 & 下一步
requests 做不到什么?
- ❌ javascript 动态渲染(如 vue / react 页面)
- ❌ 复杂登录(验证码、滑块)
- ❌ 大规模分布式爬取
进阶路线
阶段 | 技术 |
|---|---|
入门 | requests + beautifulsoup |
动态 网页 | selenium / playwright |
高效解析 | lxml / xpath |
大规模 | scrapy |
反爬对抗 | ip 代理池 / session / cookie |
十二、总结
学会 requests,你就已经掌握了爬虫的半壁江山。
你现在已经可以:
- ✅ 发送 http 请求
- ✅ 伪装浏览器
- ✅ 解析 html 数据
- ✅ 批量采集公开网页
- ✅ 保存为结构化文件
爬虫的本质不是“黑科技”,而是“自动化访问 + 数据提取”。
当你第一次用十几行代码,把一个需要手工复制半小时的网页数据一键抓下来时,那种爽感,就是编程的意义之一。
以上就是python使用requests抓取公开网页数据的详细内容,更多关于python requests抓取网页数据的资料请关注代码网其它相关文章!
发表评论