代码之家  ›  专栏  ›  技术社区  ›  welthenwel

从Python2到Python3的DeadLink异常

  •  1
  • welthenwel  · 技术社区  · 10 年前

    我发现这段用Python 2.7编写的代码在读取URL列表并检索其内容时绕过了死链接:

    for i in xrange(lines):
        try:
            t = urllib2.urlopen(urllib2.Request(lines[i]))
            deadlinkfound = False
        except:
            deadlinkfound = True
        if not(deadlinkfound):
            urllib.urlretrieve(lines[i], "Images/imag" + "-%s" % i)
    

    它在Python2中运行良好,但由于urllib2合并,我在Python3中找不到等效的。

    1 回复  |  直到 10 年前
        1
  •  0
  •   Martijn Pieters    10 年前

    你可以用 urllib.request 在这里 不要 捕捉每一个可以想象的异常,只捕捉将被合理抛出的异常:

    from urllib import request, error
    from http.client import HTTPException
    
    for i, url in enumerate(lines):
        try:
            t = request.urlopen(request.Request(url, method='HEAD'))
        except (HTTPException, error.HTTPError):
            continue
        request.urlretrieve(url, 'Images/imag-{}'.format(i))
    

    这段代码也同样,但效率更高。