我正在尝试将表单数据发布到URL。我没有得到预期的响应,并对我从请求模块(2.6.2)获得的一些信息感到好奇。以下是post方法:
>>> response = requests.post(url, data={'uname':user, 'pwd':password,'phrase':'','submit':True})
正如您所看到的,我正在使用post()
方法,因此我希望该方法为POST
。 data
对象的键与表单元素的名称匹配。 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看起来正确。如果表单发布,该页面应该返回其他内容,奇怪的是,我会检查请求标题。
>>> 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
对象及其标题。
>>> 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
属性看起来像一个查询字符串,而不像我期望的那样。
>>> 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'}
这些标题,标题中也没有表单数据。这是什么? 'Content-Type': 'application/x-www-form-urlencoded'
?这就是我的表单数据看起来像查询字符串的原因吗?普通内容类型是什么?它与Chrome报告使用同一网址所报告的类型相同,因此我怀疑这是否是问题。
如果这些都没有,那么他们可能很聪明并拒绝来自非本地的帖子吗?我主要担心的是表单数据是body
属性中的字符串,这似乎是错误的。如果没有,我可以聪明地设置HTTP标头原点吗?
答案 0 :(得分:2)
'application/x-www-form-urlencoded'
这是发布数据时的default content-type。
是的,如果您的POST数据看起来像查询字符串,那就没问题,这就是它与x-www-form-urlencoded
一起发送的方式。从上一个链接:
控件名称/值按它们在文档中出现的顺序列出。该名称与值
=
分隔开来,名称/值对由&
分隔开来。
下一步:
这些标题,标题中也没有表单数据
使用POST,表单数据不会在标题中发送。它是在请求正文中发送的。尝试
>>> response.request.body
'uname=x&pwd=y&submit=True&phrase='
查看此数据