使用 urllib.request 写入图像

Using urllib.request to write an image

我正在尝试使用此代码从给定的 URL

下载图像
import urllib.request

resource = urllib.request.urlretrieve("http://farm2.static.flickr.com/1184/1013364004_bcf87ed140.jpg")
output = open("file01.jpg","wb")
output.write(resource)
output.close()

但是,我收到以下错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-39-43fe4522fb3b> in <module>()
     41 resource = urllib.request.urlretrieve("http://farm2.static.flickr.com/1184/1013364004_bcf87ed140.jpg")
     42 output = open("file01.jpg","wb")
---> 43 output.write(resource)
     44 output.close()

TypeError: a bytes-like object is required, not 'tuple'

我知道它是 .write() 对象的错误数据类型,但我不知道如何将 resource 送入 output

对,像这样使用 urllib.request.urlretrieve

import urllib.request

resource, headers = urllib.request.urlretrieve("http://farm2.static.flickr.com/1184/1013364004_bcf87ed140.jpg")
image_data = open(resource, "rb").read()
with open("file01.jpg", "wb") as f:
    f.write(image_data)

PS: urllib.request.urlretrieve return 一个元组,第一个元素是临时文件的位置,你可以尝试获取临时文件的字节,并将其保存到新文件。

In Official document:

The following functions and classes are ported from the Python 2 module urllib (as opposed to urllib2). They might become deprecated at some point in the future.


所以我建议你使用urllib.request.urlopen,试试下面的代码:

import urllib.request

resource = urllib.request.urlopen("http://farm2.static.flickr.com/1184/1013364004_bcf87ed140.jpg")
output = open("file01.jpg", "wb")
output.write(resource.read())
output.close()