使用python请求将文件上载到表单

时间:2016-07-07 20:57:53

标签: python post file-upload scripting python-requests

尝试编写一个填写此website在线表单的脚本并上传一个zip文件。我在这里查看了the documentationseveral other posts,但仍然无法让我的脚本上传文件。

以下是文件上传的html源代码:

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)

这是我的python代码(原谅我所有的导入我一直在尝试很多不同的方法):

override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
        if segue!.identifier == "endGameSegue" {
            let vc = segue!.destinationViewController as restartScreenViewController
            vc.redWins = endGameFinalScore.redWins
            vc.blueWins = endGameFinalScore.blueWins
        }
    }

1 个答案:

答案 0 :(得分: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