Python海报内容长度错误
我在尝试用poster这个模块发送图片。虽然我按照示例来做,但对我来说并没有成功。
我的代码是:
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib, urllib2
def decaptcha(hash):
register_openers()
params = {
"file": open("captcha.jpg", "rb"),
"function" : "picture2",
"username" : "uname",
"password" : "pwd",
"pict_to" : 0,
"pict_type" : 0
}
datagen, headers = multipart_encode(params)
req = urllib2.Request("http://poster.decaptcher.com/")
solve = urllib2.urlopen(req, datagen, headers)
print solve.read()
decaptcha(None)
还有错误信息:
`File "decaptcha.py", line 27, in <module>
decaptcha(None)
File "decaptcha.py", line 24, in decaptcha
solve = urllib2.urlopen(req, datagen, headers)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 390, in open
req = meth(req)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/poster-0.8.1-py2.7.egg/poster/streaminghttp.py", line 154, in http_request
"No Content-Length specified for iterable body")
ValueError: No Content-Length specified for iterable body`
2 个回答
0
你应该把数据生成器(datagen)和请求头(headers)传给请求,而不是直接传给urlopen:
req = urllib2.Request("http://poster.decaptcher.com/", datagen, headers)
solve = urllib2.urlopen(req)
0
(免责声明:我没有使用过poster库。以下建议是我最好的猜测。)
从poster的文档来看,这个方法应该是可行的。
我会尝试以下方法(传递文件的内容,而不是打开文件的迭代器,这样应该能解决可迭代主体的问题):
params = {
"file": open("captcha.jpg", "rb").read(),
"function" : "picture2",
"username" : "uname",
"password" : "pwd",
"pict_to" : 0,
"pict_type" : 0
}
建议2:
或者可以试试: from multipart.encode import MultiPartParam
params = [
MultiPartParam("file", fileobj=open("captcha.jpg", "rb")),
("function", picture2"),
("username", "uname"),
("password", "pwd"),
("pict_to", 0),
("pict_type", 0),
]
如果这样还是出现同样的错误,可以尝试给MultiPartParam
指定filesize
参数。