2012-10-30 140 views
16

This的是,我试图使用,有我想要自动填写表单模块。我想在Mechanize上使用请求的原因是因为在使用Mechanize时,我必须首先加载登录页面,然后才能填写和提交;而通过请求,我可以跳过加载阶段并直接发布消息(希望)。基本上,我试图让登录过程消耗尽可能少的带宽。如何使用Python请求模块来模拟HTTP post请求?

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

我是怎样的一个小白,当谈到HTTP请求和诸如此类的东西,所以任何帮助,将不胜感激。供参考,这是一个学校项目。

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

+1

您可以使用Chrome检查员查看哪些值传递到由浏览器创建的发布请求中,然后从那里开始。 – bossylobster

回答

32

一些示例代码:

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 /镀铬/ IE工具无论(或只看源头))。然后找到input元素并确定所需的name属性(请参阅上文)。

您提供的网址刚好有一个“记住我”,这虽然我没有试过(因为我不能),意味着它会发出一个cookie一段时间,以避免进一步的登录 - 该cookie保存在request.session中。

那么就使用session.get(someurl, ...)检索的网页等等

+0

我尝试过,但它似乎没有验证我,虽然它使用机械化。你知道可能是错的吗? **编辑**对不起,其实它的工作。我只是犯了一个错字:) –

+0

你是一个救生员。我以为我不得不整天通过coldfusion废话。最终花15分钟做8小时手动下载! – Blairg23

+0

那么我如何发送文件? –

12

为了内的请求得到或交功能,您只需提供auth参数使用身份验证。像这样:

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

使用Chrome的开发者工具,你可以检查你的HTML页面中包含您想填写并提交表单的元素。有关如何完成的说明,请参阅here。你可以找到你需要的数据来填充你的发布请求的数据参数。如果您不担心验证正在访问的站点的安全证书,则还可以在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)