2012-10-30 136 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)