[Web自动化] 爬虫之网络请求

9.4 爬虫之网络请求

9.4.1 使用requests库发送HTTP请求

requests库提供了丰富的功能来发送HTTP请求,并处理响应。以下是一些额外的示例和说明。
发送带参数的GET请求

如果你需要向服务器发送查询参数,可以将它们作为字典传递给params参数。

python 复制代码
import requests

params = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('http://httpbin.org/get', params=params)
print(response.url)# 输出将包含查询参数:http://httpbin.org/get?key1=value1&key2=value2

发送POST请求

POST请求通常用于向服务器提交数据。你可以将数据作为字典传递给data参数(对于表单数据)或作为字节串传递给json参数(对于JSON数据)。

python 复制代码
import requests

# 发送表单数据
data = {'key': 'value'}
response = requests.post('http://httpbin.org/post', data=data)

# 发送JSON数据
json_data = {'key': 'value'}
response = requests.post('http://httpbin.org/post', json=json_data)

设置请求头

你可以通过headers参数自定义请求头,这对于模拟不同的浏览器或绕过某些服务器的检查非常有用。

python 复制代码
import requests

url = 'http://example.com'
headers = {
 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
 'Accept-Language': 'en-US,en;q=0.5',
 'DNT': '1',# Do Not Track header
 'Connection': 'keep-alive'
}

response = requests.get(url, headers=headers)

处理响应

一旦你发送了请求,requests库将返回一个Response对象。你可以使用这个对象来访问响应的内容、状态码、头部等信息。

python 复制代码
response = requests.get(url)

# 访问响应内容
print(response.text)# 文本内容
print(response.content)# 原始内容(字节串)

# 访问状态码
print(response.status_code)

# 访问响应头
print(response.headers)

# 检查请求是否成功
if response.status_code == 200:
 print("请求成功!")
else:
 print("请求失败,状态码:", response.status_code)

会话(Session)对象

如果你需要向同一个服务器发送多个请求,并且希望保持某些参数(如Cookies)在请求之间持久化,可以使用requests.Session()对象。

python 复制代码
import requests

Session = requests.Session()

# 发送第一个请求,设置Cookies
response = Session.get('http://httpbin.org/Cookies/set/SessionCookie/123456789')

# 发送第二个请求,自动携带之前的Cookies
response = Session.get('http://httpbin.org/Cookies')
print(response.text)# 输出将包含'SessionCookie: 123456789'
相关推荐
Lsx_18 分钟前
不只是 Prompt:用 Superpowers Skill 给 AI 编程装上工程化工作流
前端·ai编程·claude
小碗细面26 分钟前
前端 Prompt 工程实战:如何搭建场景化 Prompt 库
前端·ai编程
阿瑞IT29 分钟前
2026年 AI Agent 生产化落地全景:四大高频故障根因分析与工程解法
前端
木木剑光35 分钟前
我开源了一个 React 组件库,沉淀了多个高频组件和实用 Hooks
前端·javascript·react.js
kyriewen39 分钟前
DeepSeek API 高峰时段涨价 2 倍,便宜大碗的时代要结束了?
前端·ai编程·deepseek
Moment1 小时前
牛逼,NextJs 从 16.3 开始全面拥抱 Agent Native 🥰🥰🥰
前端·后端·面试
沸点小助手1 小时前
6月沸点活动获奖名单公示|本周互动话题上新🎊
前端·后端
Csvn2 小时前
React 19 `use()` 来了:以后数据加载可以不用 useEffect?
前端·react.js
没落英雄2 小时前
从零开始搭建一个 AI Agent —— LangChain + TypeScript 实战手记
前端·人工智能·架构
远航_2 小时前
git submodule
前端·后端·github