我有以下代码,可以使用 urlretrieve 抓取图像......这也是一点。
def Opt3():
global conn
curs = conn.cursor()
results = curs.execute("SELECT stock_code FROM COMPANY")
for row in results:
#for image_name in list_of_image_names:
page = requests.get('url?prodid=' + row[0])
tree = html.fromstring(page.text)
pic = tree.xpath('//*[@id="bigImg0"]')
#print pic[0].attrib['src']
print 'URL'+pic[0].attrib['src']
try:
urllib.urlretrieve('URL'+pic[0].attrib['src'],'images\\'+row[0]+'.jpg')
except:
pass
我正在读取 CSV 以输入图像名称。它可以工作,除非它遇到错误/损坏的网址(我认为没有图像)。我想知道是否可以简单地跳过任何损坏的网址并获取代码以继续抓取图像?谢谢
最佳答案
urllib 对错误捕获的支持非常差。 urllib2 是一个更好的选择。 urllib2 中的 urlretrieve
等效项是:
resp = urllib2.urlopen(im_url)
with open(sav_name, 'wb') as f:
f.write(resp.read())
要捕获的错误是:
urllib2.URLError, urllib2.HTTPError, httplib.HTTPException
如果网络出现故障,您还可以捕获socket.error
。
简单地使用 except Exception 是一个非常愚蠢的想法。它会捕获上述 block 中的每个错误,甚至是您的拼写错误。
关于python - URL检索错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24713597/