如何绕过缺失环节,继续抓好数据?

2024-04-20 00:02:52 发布

您现在位置:Python中文网/ 问答频道 /正文

如何绕过缺失环节,继续抓好数据?你知道吗

我正在使用Python2和ubuntu14.04.3。你知道吗

我正在抓取一个有多个链接到相关数据的网页。 一些相关的链接丢失,所以我需要一种方法来绕过丢失的链接,继续刮。你知道吗

Web page 1
    part description 1 with associated link
    part description 2 w/o associated link
    more part descriptions with and w/o associcated links
Web page n+
    more part descriptions

我试过:

try:
    Do some things.
    Error caused by missing link.

except Index Error as e:
    print "I/O error({0}): {1}".format(e.errno, e.strerror)
    break # to go on to next link. 
    # Did not work because program stopped to report error!

由于网页上缺少链接,所以不能使用if missing link语句。你知道吗

再次感谢您的帮助!!!你知道吗


Tags: to数据web网页链接morewithpage
2条回答

也许你在找这样的东西:

import urllib

def get_content_safe(url):
    try:
        contents = urllib.open(url)
        return contents
    except IOError, ex:
        # Report ex your way
        return None

def scrap:
    # ....
    content = get_content_safe(url)
    if content == None:
        pass # or continue or whatever
    # ....

长话短说,就像Basilevs所说的,当您捕获异常时,您的代码将不会中断并保持其执行。你知道吗

我通过遵循python2文档纠正了错误。除了更正跳转错误的网站缺失的链接,并继续对数据进行刮除。你知道吗

除更正外:

    except:
        # catch AttributeError: 'exceptions.IndexError' object has no attribute 'errno'
        e = sys.exc_info()[0]
        print "Error: %s" % e
        break

我会调查我的问题的答案。你知道吗

再次感谢您的帮助!你知道吗

相关问题 更多 >