繁体   English   中英

使用Python从某些URL下载图片

[英]Download a picture from certain URL with Python

我学习了如何使用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] >

我试图打开后一个图像URL,它可能显示为前一个,我不知道要解决它~~帮助~~~~

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

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)

我查了两个地址,第二个地址不通。 那可能是问题所在。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM