【问题标题】:Uploading a file to a form using python requests使用 python 请求将文件上传到表单
【发布时间】:2016-11-10 08:13:42
【问题描述】:

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

这里是文件上传的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)

【问题讨论】:

  • 这是你的表格,我可以向它提交测试数据吗?
  • @Bamcclur 它不是我的表格,但我想你可以向它提交测试数据,这是我的计划。不过,我也无法将文件上传到您的测试表单。

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


【解决方案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       

【讨论】:

  • 我在none-lvgvq.formstack.com/forms/test 用我自己的表单测试了这个数据 = {'form': '2408552', 'viewkey': '7e7UZhfqbU', '_submit': '1', 'field43722688- first': 'first_name', 'field43722688-last': 'last_name'} 文件 = {"field43722693": open("meh.zip", 'rb')}
  • 感谢您的快速响应!但是,它看起来仍然不像正在上传我的文件,您认为 formstack 可能会阻止我的文件上传吗?或者我这边的防火墙不允许脚本执行它?
  • @J.Blake 您是否尝试过使用我的表单数据,但字段较少?那应该可以测试你的防火墙。
  • 是的,它也没有上传到该表单。
  • @J.Blake 当您尝试发送数据时收到什么消息?使用我的表单,如果 first_name 和 last_name 字段与现有值匹配,它将不会重新提交。
猜你喜欢
  • 2017-09-02
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-11
  • 2019-05-20
  • 1970-01-01
相关资源
最近更新 更多