使用Python从某个URL下载图片

时间:2016-08-18 02:46:16

标签: python image

我学会了如何使用python从某个URL下载图片:

import urllib
imgurl="http://www.digimouth.com/news/media/2011/09/google-logo.jpg"
resource = urllib.urlopen(imgurl)
output = open("test.jpg","wb")
output.write(resource.read())
output.close()

并且效果很好,但是当我将URL更改为

  imgurl="http://farm1.static.flickr.com/96/242125326_607a826afe_o.jpg"

它不起作用,并提供了信息

File "face_down.py", line 3, in <module>
resource = urllib2.urlopen(imgurl)
File "D:\Python27\another\Lib\urllib2.py", line 154, in urlopen
return opener.open(url, data, timeout)
File "D:\Python27\another\Lib\urllib2.py", line 431, in open
response = self._open(req, data)
File "D:\Python27\another\Lib\urllib2.py", line 449, in _open
'_open', req)
File "D:\Python27\another\Lib\urllib2.py", line 409, in _call_chain
result = func(*args)
File "D:\Python27\another\Lib\urllib2.py", line 1227, in http_open
return self.do_open(httplib.HTTPConnection, req)
File "D:\Python27\another\Lib\urllib2.py", line 1197, in do_open
raise URLError(err)
urllib2.URLError: <urlopen error [Errno 10060] >

我尝试打开后一个图片网址,它可以显示为前者,我不知道解决它~~帮助~~~~

2 个答案:

答案 0 :(得分:1)

您可以尝试使用请求模块。响应将是一些字节。因此,您可以迭代这些字节块并写入文件。

import requests

url = "http://farm1.static.flickr.com/96/242125326_607a826afe_o.jpg"
r = requests.get(url)
path = "filename.jpg"
with open(path, 'wb') as f:
    for chunk in r:
        f.write(chunk)

答案 1 :(得分:0)

我查找了两个地址,第二个地址没有任何地方。这可能就是问题所在。

import urllib
imgurl="webpage url"
openimg = urllib.urlopen(imgurl) #opens image (prepares it)
img = open("test.jpg","wb") #opens the img to read it
img.write(openimg.read()) #prints it to the console
img.close() #closes img

在您的网页中再次尝试该链接,如果它出现“网页不可用”,则可能是问题。