URL检索错误处理

3 投票
3 回答
12462 浏览
提问于 2025-04-18 13:03

我有一段代码,它用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文件来输入图片的名称。这个方法基本上是有效的,但当遇到错误或损坏的链接(我想是没有图片的链接)时,就会出问题。我在想,能不能让代码跳过这些损坏的链接,继续获取其他的图片呢?谢谢!

3 个回答

-1

与其使用pass,不如在出错时试试使用continue。

try:
    urllib.urlretrieve('URL'+pic[0].attrib['src'],'images\\'+row[0]+'.jpg')

except Exception e:
    continue
3

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来捕捉错误是个很糟糕的主意,因为它会捕捉到上面所有的错误,甚至是你写错的地方。

1

如果出现错误的话,就用一个 try/except 语句,然后用 continue 来跳过这个错误继续执行。

try:
    page = requests.get('url?prodid=' +     row[0])
except Exception,e:
    print e
    continue # continue to next row

撰写回答