如何使用Python Requests模块模拟HTTP post请求?

Dis*_*ame 21 python forms post python-requests

是我正在尝试使用的模块,并且有一个我试图自动填充的表单.我想使用机械化请求的原因是因为使用Mechanize,我必须首先加载登录页面才能填写并提交,而使用请求,我可以跳过加载阶段直接发布消息(希望).基本上,我正在尝试使登录过程尽可能少地占用带宽.

我的第二个问题是,在登录过程和重定向之后,是否可能无法完全下载整个页面,而只能检索页面标题?基本上,单独的标题将告诉我登录是否成功,所以我想最小化带宽使用.

当涉及到HTTP请求等等时,我有点像菜鸟,所以任何帮助都会受到赞赏.仅供参考,这是一个学校项目.

编辑问题的第一部分已经回答.我现在的问题是第二部分

Jon*_*nts 36

一些示例代码:

import requests

URL = 'https://www.yourlibrary.ca/account/index.cfm'
payload = {
    'barcode': 'your user name/login',
    'telephone_primary': 'your password',
    'persistent': '1'  # remember me
}

session = requests.session()
r = requests.post(URL, data=payload)
print r.cookies
Run Code Online (Sandbox Code Playgroud)

第一步是查看您的源页面并确定form正在提交的元素(使用Firebug/Chrome/IE工具(或者仅查看源代码)).然后找到input元素并识别所需的name属性(见上文).

您提供的URL恰好有一个"记住我",虽然我没有尝试过(因为我不能),但暗示它会在一段时间内发出cookie以避免进一步登录 - 保留cookie在request.session.

然后只是session.get(someurl, ...)用来检索页面等...


小智 15

为了在请求get或post函数中使用身份验证,您只需提供auth参数.像这样:

response = requests.get(url, auth = ('username', 'password'))有关更多详细信息 ,请参阅"请求身份验证文档 ".

使用Chrome的开发人员工具,您可以检查包含您要填写和提交的表单的html页面元素.有关如何完成此操作的说明,请转到此处.您可以找到填充帖子请求的数据参数所需的数据.如果您不担心验证要访问的站点的安全证书,则还可以在get参数列表中指定该证书.

如果您的html页面包含用于Web表单发布的这些元素:

<textarea id="text" class="wikitext" name="text" cols="80" rows="20">
This is where your edited text will go
</textarea>
<input type="submit" id="save" name="save" value="Submit changes">
Run Code Online (Sandbox Code Playgroud)

然后发布到此表单的python代码如下:

import requests
from bs4 import BeautifulSoup

url = "http://www.someurl.com"

username = "your_username"
password = "your_password"

response = requests.get(url, auth=(username, password), verify=False)

# Getting the text of the page from the response data       
page = BeautifulSoup(response.text)

# Finding the text contained in a specific element, for instance, the 
# textarea element that contains the area where you would write a forum post
txt = page.find('textarea', id="text").string

# Finding the value of a specific attribute with name = "version" and 
# extracting the contents of the value attribute
tag = page.find('input', attrs = {'name':'version'})
ver = tag['value']

# Changing the text to whatever you want
txt = "Your text here, this will be what is written to the textarea for the post"

# construct the POST request
form_data = {
    'save' : 'Submit changes'
    'text' : txt
} 

post = requests.post(url,auth=(username, password),data=form_data,verify=False)
Run Code Online (Sandbox Code Playgroud)