[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'
相关推荐
SEO_juper5 分钟前
用 Python 写一个 GEO 可见性检查脚本:你的网站现在能被 AI 引用吗
开发语言·人工智能·爬虫·python·seo·外贸独立站
回眸&啤酒鸭23 分钟前
【回眸】OpenSwarm 多智能体协作系统实战指南
大数据·前端·人工智能
用户693717500138432 分钟前
2026,程序员的时代拐点到了
android·前端·后端
大龄秃头程序员35 分钟前
一次 iBeacon + BLE 无感解锁方案的实现记录
前端
小兔子1 小时前
Python 的 GIL 与 free-threading:3.13 之后「去 GIL」走到哪一步了
前端
IT_陈寒1 小时前
SpringBoot自动配置差点让我加班到凌晨
前端·人工智能·后端
用户8356290780511 小时前
使用 Python 对 Excel 工作表进行排序
后端·python
for_ever_love__2 小时前
MySQL 全文索引实战:FULLTEXT、ngram 中文分词与 MATCH AGAINST 到底该怎么用
java·python·mysql·全文检索·分词·索引·ngram
用户8356290780512 小时前
使用 Python 合并 PowerPoint 演示文稿
后端·python
weixin_461769402 小时前
VS Code 中创建 Jupyter 文件(.ipynb)
ide·python·jupyter