试图在python中发布多部分表单数据,不会发布

时间:2011-07-27 19:38:39

标签: python post urllib2 urllib multipartform-data

我对python很新,所以如果这很简单,我会提前道歉。我正在尝试将数据发布到python中的多部分表单。该脚本运行,但不会发布。我不确定我做错了什么。

import urllib, urllib2
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers

def toqueXF():
    register_openers()
    url = "http://localhost/trunk/admin/new.php"
    values = {'form':open('/test.pdf'),
              'bandingxml':open('/banding.xml'),
              'desc':'description'}
    data, headers = multipart_encode(values)
    request = urllib2.Request(url, data, headers)
    response = urllib2.urlopen(request)
    the_page = response.read()
    print the_page

当我调用它时,print会给我页面的html,好像我运行了“urllib2.urlopen(url)”并且没有发布任何数据:

<form enctype="multipart/form-data" action="" method="post">
    <p><input type="hidden" name="MAX_FILE_SIZE" value="1000000000" /></p>
    <p>Select PDF file to create form from: <input name="form" type="file" /></p>
    <p>(Optional): Select banding XML file: <input name="bandingxml" type="file" /></p>
    <p>Enter description of form: <input name="desc" type="text"/><br/></p>
    <p><input type="submit" value="Upload form" /></p>
</form>

海报是将数据编码为多部分/表格数据,可在此处找到:http://atlee.ca/software/poster/index.html

我在这里找到了使用海报的代码:Using MultipartPostHandler to POST form-data with Python

如果有人好奇,我会尝试在为queXF(开源光学标记识别软件)生成后自动发布pdf和xml条带文件。 http://quexf.sourceforge.net/

2 个答案:

答案 0 :(得分:1)

import urllib, urllib2
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers

def queXF():
    register_openers()
    url = "http://lilix2/trunk/admin/new.php"
    values = {'form':open('test.pdf'),
          'bandingxml':open('banding.xml'),
          'desc':'description'}
    data, headers = multipart_encode(values)
    headers['User-Agent'] = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
    request = urllib2.Request(url, data, headers)
    request.unverifiable = True
    response = urllib2.urlopen(request)
    the_page = response.read()

添加headers['User-Agent']request.unverifiable = True似乎已修复它。

答案 1 :(得分:-2)

尝试使用请求库。发布多部分文件的文档位于:http://docs.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file