Python中requests库post请求常见问题与解决方法

在网站抓包时候发送 post 内容是这样 {"index":"aaa","ignore_unavailable":true,"timeout":0,"preference":1542268295267} {"aggs":"bbb"}

多个字典

对 post 不是很了解

我用 requests 模拟 post 时候如何操作?


Python中requests库post请求常见问题与解决方法
12 回复

post 不支持多字典啊


Python中requests库post请求常见问题与解决方法

requests库的post请求常见问题主要集中在参数传递、编码、超时和异常处理上。下面我直接上代码,把几个典型场景和解决方案列出来。

1. 参数传递错误:data vs json 最常见的就是搞混datajson参数。简单说,data发送表单数据,json发送JSON数据。

import requests
import json

# 情况1:发送表单数据(application/x-www-form-urlencoded)
url = 'http://httpbin.org/post'
form_data = {'key1': 'value1', 'key2': 'value2'}
resp_form = requests.post(url, data=form_data)
print('表单响应:', resp_form.json()['form'])

# 情况2:发送JSON数据(application/json)
json_data = {'key1': 'value1', 'key2': 'value2'}
resp_json = requests.post(url, json=json_data)
print('JSON响应:', resp_json.json()['json'])

# 情况3:手动设置JSON头(有时候需要)
headers = {'Content-Type': 'application/json'}
resp_manual = requests.post(url, data=json.dumps(json_data), headers=headers)
print('手动JSON响应:', resp_manual.json()['json'])

2. 编码问题 服务器返回乱码,或者你发送的数据包含非ASCII字符时,需要指定编码。

# 设置请求和响应的编码
url = 'http://httpbin.org/post'
data = {'text': '你好,世界!'}
resp = requests.post(url, data=data)

# 确保响应编码正确(通常UTF-8)
resp.encoding = 'utf-8' if resp.encoding is None else resp.encoding
print(resp.text)

3. 超时设置 不设置超时,程序可能会一直卡住。一定要加timeout参数。

try:
    resp = requests.post('http://httpbin.org/delay/5', timeout=3)
except requests.exceptions.Timeout:
    print('请求超时!')
except requests.exceptions.RequestException as e:
    print(f'请求出错: {e}')

4. 处理SSL证书验证 访问自签名或无效证书的HTTPS站点时,可以关闭验证(生产环境慎用)。

# 跳过SSL验证(仅测试用)
resp = requests.post('https://self-signed.badssl.com/', verify=False)

# 或使用自定义证书
# resp = requests.post('https://example.com', verify='/path/to/cert.pem')

5. 会话保持和Cookie 需要保持登录状态时,用Session对象。

s = requests.Session()
s.post('http://httpbin.org/post', data={'login': 'user', 'pass': 'pass'})
# 后续请求会自动带上Cookie
resp = s.get('http://httpbin.org/cookies')
print(resp.json())

6. 上传文件 文件上传要用files参数。

files = {'file': open('test.txt', 'rb')}
resp = requests.post('http://httpbin.org/post', files=files)
print(resp.json()['files'])

7. 处理重定向和状态码 默认会自动重定向,可以通过allow_redirects控制,并检查状态码。

resp = requests.post('http://httpbin.org/redirect-to', 
                     params={'url': 'http://httpbin.org/get'},
                     allow_redirects=False)
print('状态码:', resp.status_code)
print('重定向头:', resp.headers.get('Location'))

8. 基本认证 需要HTTP Basic Auth时,直接传auth参数。

from requests.auth import HTTPBasicAuth
resp = requests.post('http://httpbin.org/post', 
                     auth=HTTPBasicAuth('user', 'pass'))

总结建议: 根据你的需求选对参数,加上超时和异常处理基本就稳了。

我也不懂,抓包出来就是显示这个

啥网站?同 1#,不支持


Accept: application/json, text/plain, /
content-type: application/x-ndjson

json 方式吗?


Accept: application/json, text/plain, /
content-type: application/x-ndjson
这个有关系吗?

1、拿到接口的 url 地址
2、查看接口是用什么方式发送( get、post 或者其他的)
3、添加请求头,请求体( header、cookies、data 之类的)
4、发送查看返回结果,校验返回结果是否正确
header 中有 application/json,post data 的时候要将字典转为 json 格式,可以用 json.dumps(data)转换一下


Accept: application/json, text/plain, /
content-type: application/x-ndjson

但是 2 个字典,我不是很懂,如何 json.dumps(data)

把两个 dict 分别 dumps, 然后用 \n 拼起来就行了, ndjson 就是 Newline delimited JSON

你用 fiddler 抓包看看 webforms 是什么结构的就很清楚了

是用 fiddler 抓包的

jsondumps,转为字符串,然后这里怎么拼的就怎么拼,以 data 的方式发就行了

回到顶部