【发布时间】:2015-07-02 14:04:13
【问题描述】:
我正在尝试将表单数据发布到 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 访问相同 URL 报告的类型相同,所以我怀疑这是问题所在。
如果这一切看起来都没有,他们可能很聪明,会拒绝来自非本地来源的帖子,对吧?我主要担心的是表单数据是body 属性中的字符串,这似乎是错误的。如果没有,我可以聪明一点,设置 HTTP 标头来源吗?
【问题讨论】:
-
我尝试用
.post(headers={'origin':...,'host':..., ...})欺骗标题,但没有任何区别。
标签: python forms http python-requests python-3.3