2011-10-13 45 views
1

我试图用poster模块发送图像。我跟着例子,但它不工作我Python海报内容长度错误

我的代码:

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` 
+0

对不起,我的代码格式化不好,我会尝试修复它。 – Meph

+0

非常感谢Aamir的格式化 – Meph

回答

0

(声明:我没有用过海报库的建议。解决方案是我最好的猜测。)

从海报文档中,它看起来好像这应该工作。

我会尝试以下方法(通过文件的内容,而不是打开文件迭代的,应该可以解决迭代身体问题):

params = { 
    "file": open("captcha.jpg", "rb").read(), 
    "function" : "picture2", 
    "username" : "uname", 
    "password" : "pwd", 
    "pict_to" : 0, 
    "pict_type" : 0 
    } 

建议2:

或者试试: 从multipart.encode import MultiPartParam

params = [ 
    MultiPartParam("file", fileobj=open("captcha.jpg", "rb")), 
    ("function", picture2"), 
    ("username", "uname"), 
    ("password", "pwd"), 
    ("pict_to", 0), 
    ("pict_type", 0), 
] 

如果失败时出现相同的错误,请尝试指定影响filesize参数到MultiPartParam

+0

感谢您的回答,但即使指定了文件大小,它仍然无法正常工作。同样的错误。 – Meph

+0

@Meph:你有没有想过这个? – codeape

+0

不幸的是没有 – Meph

0

你应该通过datagen和头文件要求,不是的urlopen:

req = urllib2.Request("http://poster.decaptcher.com/", datagen, headers) 
solve = urllib2.urlopen(req) 
+0

我当时都尝试过,但零成功。 – Meph