如何使用发布请求填写表单并获得响应

时间:2018-01-11 02:36:17

标签: python python-requests

我的表格如下:

/usr/src/app/.tmp

所以,基本上表单有两个选项,State和Population,每个都有一些选项..想法是从表单中选择选项然后提交。

在提交时,结果显示在同一页面中。

所以,基本上我如何在python中提交这个帖子请求...然后得到结果(当按下提交时......页面会刷新结果?) 如果这有意义,请告诉我? 感谢

1 个答案:

答案 0 :(得分:4)

您要做的是向POST

提交http://example.com/showtree.jsp请求

使用requests库(推荐)

参考:http://docs.python-requests.org/en/master/

requests库极大地简化了HTTP请求,但是是一个额外的依赖

import requests

# Create a dictionary containing the form elements and their values
data = {"state": "ca", "population": 100}

# POST to the remote endpoint. The Requests library will encode the
# data automatically
r = requests.post("http://example.com/showtree.js", data=data)

# Get the raw body text back
body_data = r.text

使用内置的urllib

此处的相关答案:Python - make a POST request using Python 3 urllib

from urllib import request, parse

# Create a dictionary containing the form elements and their values
data = {"state": "ca", "population": 100}

# This encodes the data to application/x-www-form-urlencoded format
# then converts it to bytes, needed before using with request.Request
encoded_data = parse.urlencode(data).encode()

# POST to the remote endpoint
req =  request.Request("http://example.com/showtree.js", data=encoded_data)

# This will contain the response page
with request.urlopen(req) as resp:
    # Reads and decodes the body response data
    # Note: You will need to specify the correct response encoding
    #       if it is not utf-8
    body_data = resp.read().decode('utf-8')

编辑:附录

根据t.m.adam的评论添加,

以上示例是向大多数URI端点(如API或基本网页)提交POST请求的简化方法。

然而,有一些常见的并发症:

1)有CSRF令牌

...或其他隐藏字段

隐藏字段仍会显示在<form>的源代码中(例如<input type="hidden" name="foo" value="bar">

如果隐藏字段在每个表单加载中保持相同的值,则只需将其包含在标准数据字典中,即

data = {
    ...
    "foo": "bar",
    ...
}

如果隐藏字段在页面加载之间发生变化,例如一个CSRF令牌,你必须首先加载表单的页面 (例如,带有GET请求),解析响应以获取表单元素的值,然后将其包含在数据字典中< / p>

2)页面需要您登录

......或其他需要Cookie的情况。

您最好的方法是制作系列请求,在正常使用目标网页之前完成所需的步骤(例如,向登录表单提交POST请求)

您需要使用“饼干罐”。此时我真的开始推荐requests库;您可以阅读有关cookie处理的更多信息here

3)Javascript需要在目标表单上运行

有时,表单需要在提交之前运行Javascript。

如果你不幸有这样的表格,不幸的是我建议你不再使用python,并切换到某种无头浏览器,如PhantomJS

(可以使用像Selenium这样的库来控制PhantomJS;但是对于简单的项目,可能更容易直接使用PhantomJS)

相关问题