编程语言
首页 > 编程语言> > 试图在python中发布多部分表单数据,不会发布

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

作者:互联网

我对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>

poster是将数据编码为multipart / form数据,可以在这里找到:http://atlee.ca/software/poster/index.html

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

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

解决方法:

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()

添加标题[‘User-Agent’]和request.unverifiable = True似乎修复了它.

标签:python,post,urllib,urllib2,multipartform-data
来源: https://codeday.me/bug/20191006/1863157.html