Python请求在尝试用D进行POST时发生getting TypeError

2024-04-19 00:40:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图做一个网页上的表单登录,我不断得到下面的类型错误。我已经阅读了Python Requests package文档,当我打印数据字典时,它看起来像是一个有效的例子。我不确定出了什么问题。这是我的回溯代码:

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)发布时,发布成功。我不知道这是怎么回事。你知道吗


Tags: urldataapplicationusernamepasswordxmlpostrequests
2条回答

根据requests API,看起来好像您的headers参数需要关键字,如果没有关键字,post()就假定它是data。试试这个:

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

一些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

相关问题 更多 >