2016-07-30 14 views
-2

我試圖自動化與python腳本的captcha文件識別。 但是,經過幾天的努力,我的功能似乎遠非預期的結果。AttributeError:__exit__緩衝下載的圖像在Python 2.7

此外,我得到的追蹤信息不足以幫助我進一步調查。

這裏是我的功能:

def getmsg(): 
    solved = '' 
    probe_request = [] 
    try: 
     probe_request = api.messages.get(offset = 0, count = 2) 
    except apierror, e: 
     if e.code is 14: 
      key = e.captcha_sid 
      imagefile = cStringIO.StringIO(urllib.urlopen(e.captcha_img).read()) 
      img = Image.open(imagefile) 
      imagebuf = img.load() 
      with imagebuf as captcha_file: 
       captcha = cptapi.solve(captcha_file) 
    finally: 
     while solved is None: 
      solved = captcha.try_get_result() 
      tm.sleep(1.500) 
     print probe_request 

這裏是回溯:

Traceback (most recent call last): 
    File "myscript.py", line 158, in <module> 
    getmsg() 
    File "myscript.py", line 147, in getmsg 
    with imagebuf as captcha_file: 
AttributeError: __exit__ 

有人請澄清正是我做錯了嗎?

而且我沒跟圖像處理無緩衝成功:

key = e.captcha_sid 
response = requests.get(e.captcha_img) 
img = Image.open(StringIO.StringIO(response.content)) 
with img as captcha_file: 
    captcha = cptapi.solve(captcha_file) 

導致:

captcha = cptapi.solve(captcha_file) 
    File "/usr/local/lib/python2.7/dist-packages/twocaptchaapi/__init__.py", line 62, in proxy 
    return func(*args, **kwargs) 
    File "/usr/local/lib/python2.7/dist-packages/twocaptchaapi/__init__.py", line 75, in proxy 
    return func(*args, **kwargs) 
    File "/usr/local/lib/python2.7/dist-packages/twocaptchaapi/__init__.py", line 147, in solve 
    raw_data = file.read() 
    File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 632, in __getattr__ 
    raise AttributeError(name) 
AttributeError: read 

回答

0

imagebuf不是context manager。您不能在with語句中使用它,該語句通過首先存儲contextmanager.__exit__ method來測試上下文管理器。沒有必要關閉它。

cptapi.solve需要一個類似文件的對象;從solve() docstring

Queues a captcha for solving. file may either be a path or a file object.

有在一個Image對象路過此地沒有意義的,只是通過在StringIO實例,而不是:

imagefile = cStringIO.StringIO(urllib.urlopen(e.captcha_img).read()) 
captcha = cptapi.solve(imagefile) 

同樣,也沒有必要使用接近這裏對象,你不需要使用with

+0

非常感謝。問題解決了。 – unexposed