Python爬虫requests发送POST请求的三种方式详解
本文详解Python爬虫中requests库发送POST请求的三种核心方式:Form表单、JSON数据及文件上传。通过httpbin.org测试接口,展示data与files参数的具体用法、Content-Type头部的自动处理及返回结果解析,帮助开发者掌握不同场景下的数据提交技巧。
POST请求的三种常见提交方式
在HTTP协议中,POST请求的数据必须包含在消息主体(Body)中。服务端通过请求头中的 Content-Type 字段来识别数据的编码格式,从而正确解析请求内容。常见的POST提交方式主要有以下三种:
- application/x-www-form-urlencoded:最常见的表单提交方式,数据格式为键值对。
- application/json:用于以JSON字符串格式提交数据,常用于API接口。
- multipart/form-data:通常用于上传文件,支持混合提交表单字段和文件。
方式一:发送Form表单数据
当需要提交传统的Form表单数据时,可以将字典直接赋值给 requests.post() 的 data 参数。此时,requests库会自动将字典序列化为 application/x-www-form-urlencoded 格式,并设置相应的Content-Type头部。
# -*- coding: utf-8 -*-
# author:Gary
import requests
url = 'http://httpbin.org/post' # 一个测试网站的url
data = {'key1': 'value1', 'key2': 'value2'} # 你发送给这个的数据
r = requests.post(url, data=data) # 使用requests的post方法,data接受你想发送的数据
print(r.text) # 查看返回的内容执行上述代码后,服务端返回的JSON响应中,form 字段将包含提交的键值对,而 json 字段为 null。响应示例如下:
{
"args": {},
"data": "",
"files": {},
#你提交的表单数据
"form": {
"key1": "value1",
"key2": "value2"
},
"headers": {
……
"Content-Type": "application/x-www-form-urlencoded",
……
},
"json": null,
……
}方式二:发送JSON数据
若需以JSON格式提交数据,需先将字典序列化为JSON字符串,再赋值给 data 参数。此时,requests库会自动将Content-Type设置为 application/json。
# -*- coding: utf-8 -*-
# author:Gary
import requests
import json
url = 'http://httpbin.org/post' # 一个测试网站的url
json_data = json.dumps({'key1': 'value1', 'key2': 'value2'}) # 你发送给这个的数据,数据格式转为json
r = requests.post(url, data=json_data) # 使用requests的post方法,data接受你想发送的数据
print(r.text) # 查看返回的内容服务端返回的响应中,json 字段将解析后的JSON对象,而 form 字段为空。响应示例如下:
{
"args": {},
"data": "{\"key2\": \"value2\", \"key1\": \"value1\"}",
"files": {},
"form": {},
"headers": {
……
"Content-Type": "application/json",
……
},
"json": {
"key1": "value1",
"key2": "value2"
},
……
}方式三:上传文件
当需要上传文件时,应使用 files 参数。该参数接受一个字典,键为字段名,值为打开的文件对象。requests库会自动将Content-Type设置为 multipart/form-data,并生成相应的boundary。
# -*- coding: utf-8 -*-
# author:Gary
import requests
url = 'http://httpbin.org/post'
files = {'file': open('report.txt', 'rb')} # 目录下得有report.txt文件才能上传,rb是指以二进制格式打开一个文件用于只读。
r = requests.post(url, files=files) # 通过files参数指定你想发送的文件的内容
print(r.text)服务端返回的响应中,files 字段将包含上传文件的内容,而 form 和 json 字段为空。响应示例如下:
{
"args": {},
"data": "",
"files": {
"file": "Hello world!"
},
"form": {},
"headers": {……
"Content-Type": "multipart/form-data; boundary=467e443f4c3d403c8559e2ebd009bf4a",
……
},
"json": null,
……
}以上就是Python爬虫使用requests发送POST请求的三种常见方式的详细内容,更多关于Python爬虫requests POST请求的资料请关注本站其它相关文章!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









