2013-07-18 80 views
3

我需要登錄並上傳文件。我面臨的問題是,登錄頁面與上傳頁面不同。如果必須手動完成,我將登錄(login.php)到該網站,然後導航到上載頁面(uploader.php)以上載文件。這是我寫的:使用Python'請求'登錄並上傳文件

import requests 

url1='http://www.abc.com/login.php' 
r = requests.post(url1, auth=('uname', 'pword')) 
print r.status_code //msg:'200' 

payload = {'upload':open('./tmp.txt')} 
url2='http://www.abc.com/uploader.php' 
r = requests.post(url2, data=payload) 
print r.text //msg: "you must first login to upload the file" 

我的代碼顯然不按預期工作。登錄部分正常工作,但沒有上傳部分。 請如何完成我的目標。

UPDATE:

爲了讓更深入地瞭解我的問題,我給login.phpuploader.php文件的詳細信息:

的login.php

<form method="POST" action="login.php" class="login"> 
<input type="text" name="username"></input> 
<input type="password" name="password"></input>   
<input type="submit" value="Login"></input> 

uploader.php

<form action='uploader.php' method='POST' id='form' class='upload' enctype="multipart/form-data" > 
<input type='file' name='upload' id='file'></input> 
<input type='button' value='Analyze' name='button' onclick='javascript: checkuploadform(false)'> 
+0

哪裏是你說你的代碼將要發佈? – svineet

+0

我已經發布了它。爲什麼不可見? – Maggie

+0

好吧,現在可見 – svineet

回答

4

做一個會話,然後使用該會話做你的請求 -

sessionObj = requests.session() 
sessionOj.get(...) # Do whatever ... 

環節仍然存在你的cookies爲將來的請求。
並使用post參數作爲用戶名,密碼作爲參數需要登錄login.php,而不是auth用戶名密碼。
還使用files參數來上傳文件。 所以最終的代碼 -

import requests 

sessionObj = requests.session() 
url1='http://www.abc.com/login.php' 
r = sessionObj.post(url1, params={'username':'usernamehere' , 'password':'password here'}) 
print r.status_code //msg:'200' 


filehandle = open('./tmp.txt') 
url2='http://www.abc.com/uploader.php' 
r = sessionObj.post(url2, data={},files = {'upload':filehandle}) 
print r.text 

Docs.

+0

謝謝你的答案。但是,我仍然得到這個錯誤。我已經更新了這個問題,以更深入地瞭解'login.php'和'uploader.php' – Maggie