【发布时间】:2017-05-26 13:32:41
【问题描述】:
我想使用 python 通过其 url 将图像下载到本地目录。 我的方法是使用“urllib2”包下载。代码是
def download(url, filename):
f = open(filename, "wb")
headers = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'}
req = urllib2.Request(url=url, headers=headers)
f.write(urllib2.urlopen(req, timeout=10).read())
f.close()
我在大多数 url 中都成功了,但对于某些 url 我失败了,即使有更多的超时秒数。
这些“奇怪”网址的一些失败示例:
https://s-media-cache-ak0.pinimg.com/736x/c0/95/5d/c0955d6d0ffe6145924d4e7d252cde4e.jpg https://smhttp-ssl-33667.nexcesscdn.net/manual/wp-content/uploads/2016/10/navy-suit-blue-shirt-men-look.jpg http://1.bp.blogspot.com/ExAqpPuUKM4/Uzq6mXbda2I/AAAAAAAAEL4/c_xgff8HMNU/s1600/1890361_801417276554561_1726056762_o.jpg
我使用“try”和“excpet”来获得 excpetion。 尝试: 下载(网址,文件名) 除了例外,e: 打印异常,':',e
有几种错误:
<type 'exceptions.Exception'> : <urlopen error [Errno 65] No route to host>
<type 'exceptions.Exception'> : [Errno 54] Connection reset by peer
<type 'exceptions.Exception'> : timed out
我尝试了其他下载工具,但它们也不起作用。但是当我尝试使用 Chrome 或 Safari 等浏览器时,图像加载良好。
谁能帮我解决这个问题?
【问题讨论】:
-
根据例外情况,您似乎遇到了网络问题或远程端有问题。我尝试使用请求下载它们,它只适用于我的位置。
标签: python image web-crawler urllib2