【问题标题】:Python Requests getting TypeError when attempting to POST with Data尝试使用数据进行 POST 时 Python 请求获取 TypeError
【发布时间】:2019-03-09 02:52:01
【问题描述】:

我正在尝试在页面上进行表单登录,但我不断收到以下类型错误。我已经阅读了Python Requests package 文档,当我打印我的数据字典时,它看起来像是一个有效的示例。我不确定出了什么问题。这是我的 Traceback 代码:

import requests

accept = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
acceptlang = "en-US,en;q=0.9"
url = 'https://httpbin.org/post'
userid = 'username'
passwd = 'password'

headers = {
        'Accept': accept,
        'Accept-Language': acceptlang,
    }

data = {userid: fakeuserid, passwd: fakepasswd}

>>> print(data)
{'username': 'fakeuser@example.com', 'password': '0#CCJyy3^5Tu(Z'}
>>> response = requests.post(url, headers, data=data)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: post() got multiple values for argument 'data'

当我仅使用 (url, headers) 或 (url, data=data) 发布时,发布成功。我不确定这里发生了什么。

【问题讨论】:

    标签: python python-3.x post python-requests


    【解决方案1】:

    根据requests API,您似乎需要headers 参数的关键字,没有它post() 假定它是data。试试这个:

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

    【讨论】:

      【解决方案2】:

      一些 API 服务器只接受 JSON 编码的 POST/PATCH 数据,这样做:

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

      和下面的一样:

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

      查看更多信息:docs.python-requests.org/en/master/user/quickstart/#more-complicated-post-requests

      【讨论】:

      • 请添加您的代码说明,以便我们知道它的作用和原因。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-22
      • 1970-01-01
      • 2021-12-13
      • 2019-09-05
      • 1970-01-01
      • 2016-12-18
      相关资源
      最近更新 更多