2013-03-08 43 views
1

我是網站開發的新手,所以如果下面的問題聽起來有點幼稚,那麼請仁慈。我如何使用python發佈到web表單?我知道網絡的形式是這樣的,我要上傳本地文件爲它在線處理,並得到返回的數據發佈數據到網絡進行處理

<form action="process.php" method="post" enctype="multipart/form-data"> 
    <input type="file" name="file" id="file" id="chooser" /><br /> 
    <input type="submit" value="Upload" name="submit" /> 
</form> 

這裏就是我有我的Python程序爲止。

upfile = urllib.urlencode({'file':path/to/my/local/file}) 
filehandle = urllib.urlopen('http://www.comdroid.org/', upfile) 
soup = BeautifulSoup(filehandle) 
print soup 

我想看到返回的結果,但目前的代碼片段只給了我不處理我上傳的文件的結果。有什麼我缺少

------------ UPDATE ---------------- 這裏是我如何做到這一點現在

import urllib2 
import urllib 
import requests 
import os 
files1 ={'file':open('/opt/apps/au.com.psyborg.sbc-5.apk','rb')‌​} 
#response= os.system("curl --form [email protected]/opt/apps/au.com.psyborg.sbc-5.apk --form submit=Upload www.comdroid.org/process.php") 
req = requests.post('comdroid.org/process.php', files = files1) 
print req.text 

奇怪的是,我不能要求這樣做,服務器抱怨我的文件不是.apk文件,它實際上是。但如果我使用os.system作爲註釋切換到curl,它就可以工作!所以我懷疑我在請求中錯過了一些東西。任何建議?

回答

2

如果你看看錶格的action屬性,它會去process.php - 所以你需要發送你的文件上傳到http://www.comdroid.org/process.php

做文件上傳與標準庫是一個有點疼痛的 - 如果你允許,我會建議使用requests此 - 他們甚至have an example of what you're asking for in their documentation

url = 'http://httpbin.org/post' 
files = {'file': open('report.xls', 'rb')} 
r = requests.post(url, files=files) 

我還發現this SO answer on how to do it with the mechanize library,並a code sample that might help if you want to do it with the standard library

+0

謝謝,我現在瞭解整個框架,但仍然無法獲得所需的結果。發生了什麼事是服務器不斷拒絕我的要求說我的文件不是必需的.apk文件(實際上它是。 – Daniel 2013-03-09 17:17:41

+0

請參閱我的更新 – Daniel 2013-03-09 17:26:35

+0

是否有可能「請求」的方式編碼.apk文件以某種方式扭曲它和.apk文件無法被服務器識別? – Daniel 2013-03-09 17:27:57