2013-05-15 29 views
0

我試圖用shutil/urlopen下載圖像,因爲不推薦?我不確定它是否被棄用,但urlretrieve不下載該文件,它只是創建映像名稱的文件夾。看過其他問題後,我看到一個提供此代碼的問題,但是我也發現了一個錯誤。下載Web圖像瓦特/ urlopen/shutil:錯誤__exit__

from urllib2 import urlopen 
from shutil import copyfileobj 


url = 'http://www.watchcartoononline.com/thumbs/South-Park-Season-14-Episode-11-Coon-2-Hindsight.jpg' 
path = 'image.jpg' 

with urlopen(url) as in_stream, open(path, 'wb') as out_file: 
    copyfileobj(in_stream, out_file) 

輸出

with urlopen(url) as in_stream, open(path, 'wb') as out_file: 
AttributeError: addinfourl instance has no attribute '__exit__ 

回答

1

試試這個:

import urllib 
urllib.urlretrieve("http://url/img.jpg", "img.jpg") 
+0

正如我在這個問題中所說的,urlretrieve不會工作,因爲網站即時下載從它的圖像不贊成 – Crispy

+0

@Crispy:你確定不推薦使用你正在尋找的詞嗎? – Blender

+0

我可能在術語上有錯,因爲我在編程方面的術語不太好。 – Crispy

2

urlopen沒有實現上下文管理器,所以你不能在with塊使用它。這裏是bug report

您可以使用contextlib.closing來包裝它,雖然上面的錯誤報告也提到了一些問題。

注意:這僅適用於Python的< 3.2

1

urlopen不是在Python 2上下文管理器(我不知道3)。您必須手動打開和關閉它:

in_stream = urlopen(url) 

with open(path, 'wb') as out_file: 
    copyfileobj(in_stream, out_file) 

in_stream.close() 

您也可以只使用urllib.urlretrieve

import urllib 

urllib.urlretrieve(url, path) 

它讀取的塊/寫,你乾淨下載大文件,它可以讓。