您的位置 首页 知识

python post返回值 Pythonrequests.post返回406错

python post返回值 Pythonrequests.post返回406错

目录
  • 解决 Python requests.post() 返回 406 错误
  • 难题分析,最好的技巧还是一段代码一段代码的调试
  • 常见缘故及解决方案
    • 1. 请求头 (headers) 难题
    • 2. 数据格式难题
    • 3. 用户代理难题
    • 4. 认证难题
    • 5. 服务器端限制
  • 完整示例

    解决 Python requests.post() 返回 406 错误

    HTTP 406 "Not Acceptable" 错误表示服务器无法生成符合客户端请求中 Accept 头部指定的响应内容。

    难题分析,最好的技巧还是一段代码一段代码的调试

    今天是模型一个登录的脚本,以前都用得好好的,现在突然不行了,出现了406的错误,觉得有点奇怪,代码如下:

    header = ‘Content-Type’:’application/x-www-form-urlencoded’,’User-Agent’:’Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36’form_data = “actionFlag”:”login”, “uid”:”xxxxx”, “password”:”xxxxx”}data = parse.urlencode(from_data)response = request.post(url=login_url,header=header, data = data, verify=False)

    以前上面这段代码是没有什么难题的,但最近才发现一直是406,跟踪到代码中的 sessions.py中adapter的值是对的,上面是显示访问成功而且返回值是200,这说明访问代码是没有难题的,但什么时候出的难题呢?继续往下

    发现了这一段代码,其中allow_redirects的值就有点意思了,这个值的默认值是Ture,但我们登录后,后面肯定有一个redirect的,也就是说后面那个跳转的地址有难题了,因此才会导致出难题

    常见缘故及解决方案

    1. 请求头 (headers) 难题

    确保你的请求头中包含正确的AcceptContent-Type

    headers = ‘Accept’: ‘application/json’, 或其他服务器期望的类型 ‘Content-Type’: ‘application/json’, 或其他适当的内容类型 其他必要的头部,如授权信息}

    2. 数据格式难题

    确保发送的数据格式与Content-Type头部匹配:

    import jsondata = ‘key’: ‘value’}response = requests.post(url, data=json.dumps(data), headers=headers)

    或者使用json参数自动处理:

    response = requests.post(url, json=data, headers=headers)

    3. 用户代理难题

    有些服务器要求特定的 User-Agent:

    headers = ‘User-Agent’: ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) …’, 其他头部}

    4. 认证难题

    如果 API 需要认证,确保提供了正确的凭证:

    headers = ‘Authorization’: ‘Bearer your_token_here’, 其他头部}

    5. 服务器端限制

    检查 API 文档,确认:

    • 是否支持 POST 技巧
    • 是否接受你发送的内容类型
    • 是否有其他独特要求

    完整示例

    import requestsimport jsonurl = ‘https://api.example.com/endpoint’headers = ‘Accept’: ‘application/json’, ‘Content-Type’: ‘application/json’, ‘User-Agent’: ‘MyApp/1.0’, ‘Authorization’: ‘Bearer abc123…’}data = ‘key1’: ‘value1’, ‘key2’: ‘value2’}try: response = requests.post(url, json=data, headers=headers) response.raise_for_status() 如果响应情形码不是200,抛出异常 print(response.json())except requests.exceptions.RequestException as e: print(f”请求失败: e}”)

    如果难题仍然存在,建议:

    1. 检查 API 文档的具体要求
    2. 使用开发者工具查看浏览器发送的成功请求的格式
    3. 联系 API 提供商获取支持

    到此这篇关于Python requests.post()返回406错误的常见缘故及解决方案的文章就介绍到这了,更多相关Python requests.post()返回406内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!

    无论兄弟们可能感兴趣的文章:

    • Python爬虫报错<response[406]>(已解决)
    • PythonRequests.post()请求失败时的retry设置方式
    • Pythonrequests.post()技巧中data和json参数的使用技巧