2016-07-07 41 views
0

試圖編寫一個腳本,填寫此website的在線表單並上傳zip文件。我已經看過the documentationseveralotherposts在這裏,但仍然不能讓我的腳本上傳文件。使用python請求將文件上傳到表單

下面是文件上傳的HTML源代碼:

<input type="file" id="field19567427" name="field19567427" 
size="30" class="fsField fsUpload uploadTypes-jpg,jpeg,gif,png,bmp,tif, 
doc,docx,xls,xlsx,txt,mp3,mp4,aac,wav,au,wmv,avi,mpg,mpeg,zip,gz,rar,z,tgz,tar,sitx" /> 

這裏是我的Python代碼(原諒我所有的進口我一直在嘗試很多不同的方法):

import urllib 
import urllib2 
import cookielib 
import webbrowser 
import os 
import base64 
import requests 
from pprint import pprint 

walla = "X:\\Test\\Test.html" 
my_file = open("X:\\Some_Directory\\Meh.zip", 'rb') 
values = { 
    "field19567029" : "Some Company", 
    "field20044433" : "Some Email", 
    "field40168419" : "Some Phone Num", 
    "field19567035" : "Some Code", 
    "field19567303" : "Some Distance", 
    "field19567306" : "Map Projection", 

    } 
zippy = { 
    "field19567427" : my_file 
    } 

url = "http://www.formstack.com/forms/?1455656-XG7ryB28LE" 
url2 = "http://httpbin.org/post" 
if os.path.exists(walla): 
    os.remove(walla) 
r = requests.post(url, data=values, files=zippy) 
#r.status_code 
#pprint(r.json()['headers']) 
with open(walla, "w") as f: 
    f.write(r.content) 
+0

這是你的米,我可以提交測試數據嗎? – Bamcclur

+0

@Bamcclur它不是我的形式,但我想你可以提交測試數據給它,這是我的計劃。但我也無法將文件上傳到測試表單。 –

回答

1

與您的具體網址,您需要添加一些數據:

url = "http://www.formstack.com/forms/?1455656-XG7ryB28LE" 

session = requests.session() 
r = session.get(url) # This can be used to determine form and viewkey values 

data = { 
    "form": "1455656", # Added 
    "viewkey": "XG7ryB28LE", # Added 
    "_submit": "1", # Added 
    "field19567029" : "Some Company", 
    "field20044433" : "Some Email", 
    "field40168419" : "Some Phone Num", 
    "field19567035" : "Some Code", 
    "field19567303" : "Some Distance", 
    "field19567306" : "Map Projection", 
    } 

files = {"field19567427": open("X:\\Some_Directory\\Meh.zip", 'rb')} 

r2 = session.post(url, data=data, files=files) 
print r2.content  
+0

我在https://none-lvgvq.formstack.com/forms/test中使用data = {'form':'2408552','viewkey':'7e7UZhfqbU','_submit':'1 ','field43722688-first':'first_name','field43722688-last':'last_name'} files = {「field43722693」:open(「meh.zip」,'rb')} – Bamcclur

+0

感謝您的快速響應!然而,它仍然看起來不像它正在上傳我的文件你認爲堆棧可能會阻止我的文件上傳?或者也許我的一個防火牆不允許腳本執行它? –

+0

@ J.Blake您是否嘗試過使用我的表單數據,使用更少的字段?這應該能夠測試你的防火牆。 – Bamcclur