繁体   English   中英

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

[英]How to simulate HTTP post request using Python Requests module?

是我要使用的模块,并且有一张我要自动填写的表格。 我想在Mechanize上使用Requests的原因是,在使用Mechanize时,我必须先加载登录页面,然后才能填写并提交,而在Requests中,我可以跳过加载阶段,直接进入发布消息(希望)。 基本上,我试图使登录过程消耗的带宽尽可能少。

我的第二个问题是,在登录过程和重定向之后,是否可能无法完全下载整个页面,而只能检索页面标题? 基本上,仅标题会告诉我登录是否成功,所以我想最大程度地减少带宽使用。

对于HTTP请求和其他方面,我还是个菜鸟,所以可以提供任何帮助。 仅供参考,这是用于学校项目。

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

一些示例代码:

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

第一步是查看您的源页面,并确定要提交的form元素(使用Firebug / Chrome / IE工具(或其他方式)(或仅查看源代码))。 然后找到input元素并标识所需的name属性(请参见上文)。

您提供的URL恰好有一个“记住我”字样,尽管我没有尝试过(因为我不能这样做),但它暗示它会发布cookie一段时间以避免再次登录-cookie会保留在request.session

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

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

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

使用Chrome的开发者工具,您可以检查html页面中包含要填写和提交的表单的元素。 有关如何完成此操作的说明,请转到此处 您可以找到填充帖子请求的data参数所需的数据。 如果您不担心要验证所访问站点的安全证书,则还可以在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">

然后发布到此表单的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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM