Python 请求模块不使用 post 方法

Python requests module not using post method

我正在尝试 post 将数据形成 URL。我没有得到预期的响应,并且对我从请求模块 (2.6.2) 获得的一些信息感到好奇。以下是post方法:

>>> response = requests.post(url, data={'uname':user, 'pwd':password,'phrase':'','submit':True})

如您所见,我正在使用 post() 方法,所以我希望该方法是 POSTdata object 的键与表单元素的名称相匹配。 URL 是表单操作。

>>> vars(response.request)
{'method': 'GET', 'body': None, '_cookies': <<class 'requests.cookies.RequestsCookieJar'>[]>, 'headers': {'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'python-requests/2.6.2 CPython/3.3.6 Windows/8', 'Connection': 'keep-alive'}, 'hooks': {'response': []}, 'url': url}

response.request 属性 应包含有关为此响应发送的请求的信息。是method 属性 是GET,我预计POST。 URL 看起来是正确的。如果表单 posts,该页面预计会 return 其他内容,但是很奇怪,我会检查请求 headers.

>>> response.request.headers
{'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'python-requests/2.6.2 CPython/3.3.6 Windows/8', 'Connection': 'keep-alive'}
>>> 

除了这些看起来还不错,等一下!我的表单数据在哪里?为什么不随请求一起发送?我检查了历史记录,发现我正在被重定向。这次我将 allow_redirects=False 添加到我的 post() 调用中。然后检查 response.request object 及其 headers.

>>> vars(response.request)
{'method': 'POST', 'body': 'phrase=&pwd=****&uname=****&submit=True', '_cookies': <<class 'requests.cookies.RequestsCookieJar'>[]>, 'headers': {'Accept-Encoding': 'gzip, deflate', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'python-requests/2.6.2 CPython/3.3.6 Windows/8', 'Content-Length': '56', 'Accept': '*/*', 'Connection': 'keep-alive'}, 'hooks': {'response': []}, 'url': 'http://myurl.com/path/to/script.php'}

这次是 POST 所以这似乎是正确的。我觉得我走在正确的轨道上。真奇怪,body 属性 看起来像一个查询字符串,不像我期望的形式 post.

>>> response.request.headers
{'Accept-Encoding': 'gzip, deflate', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'python-requests/2.6.2 CPython/3.3.6 Windows/8', 'Content-Length': '56', 'Accept': '*/*', 'Connection': 'keep-alive'}

那些 headers,在 header 中同样没有表单数据。这是什么? 'Content-Type': 'application/x-www-form-urlencoded'?这就是我的表单数据看起来像查询字符串的原因吗?正常的 content-type 是什么?它与 Chrome 报告的类型相同,点击相同的 URL 所以我怀疑这就是问题所在。

如果 none 看起来不对,他们可能很聪明,拒绝了来自 non-local 来源的 post 对吧?我主要担心的是表单数据是 body 属性 中的字符串,这似乎是错误的。如果没有,我可以聪明地设置 HTTP header 来源吗?

'application/x-www-form-urlencoded'

这是发布数据时的default content-type

是的,如果您的 POST 数据看起来像查询字符串也没关系,这就是它通过 x-www-form-urlencoded 发送的方式。从上一个link:

The control names/values are listed in the order they appear in the document. The name is separated from the value by = and name/value pairs are separated from each other by &.

下一个:

Those headers, again no form data in the header

使用 POST,表单数据不会在 header 中发送。它在请求的 body 中发送。尝试

>>> response.request.body
'uname=x&pwd=y&submit=True&phrase='

查看此数据