0
我有包含图像的文本文件,我有一个目录,我想要保存图像。在python错误处理中下载图像
import os
import urllib
import sys
def normalize(url):
url = url.split("/")[-1]
return url.split("\n")[0]
def main():
out_dir = "Workspace/cnf/img"
with open('cnf/image_flower.txt') as url_array:
for url in url_array:
try:
urllib.urlretrieve(url, os.path.join(out_dir, normalize(url)))
except Exception as e :
print "Exception|",e,"|",url
print("Images Downloaded")
的main()
我得到我面临以下问题 1.I想抓住所有的HTTP错误代码和打印一样找不到网页的images.But都挺error.which我的代码无法打印。 2.我有大约100,000个网址,所以我的代码花了很多时间。
可否请你建议我一个更好的方式来处理它
我的代码工作正常。我想要的是捕获是否有http error.like页面找不到,这种尝试和异常无法处理。 – akira
尝试打印出您的例外中的错误状态代码 'print e.code' 如果它返回404,那么它是页面未找到错误。 然后你可以使用If if 'if e.code == 404: #do stuff .. else:' 如果它仍然不适用于你,也可以检出urllib2.HTTPError。 –