Python 网页抓取,如果错误则跳过 url

tha*_*rey 0 python error-handling web-scraping python-requests

我正在尝试抓取一个网站(大约 7000 个链接,全部在一个列表中),由于我的方法,它需要很长时间,我想我对此没有意见(因为这意味着不被发现)。但是,如果我在尝试检索页面时遇到任何类型的错误,我可以跳过它吗?现在,如果出现错误,代码就会中断并给出一堆错误消息。这是我的代码:

Collection是列表的列表和结果文件。基本上,我试图运行一个循环get_url_data()(我有一个之前的问题要感谢),我的所有网址都在urllist. 我有一个叫做HTTPError但似乎不能处理所有错误的东西,因此这篇文章。在相关的支线任务中,获得无法处理的网址列表也很好,但这不是我主要关心的问题(但如果有人能告诉我如何处理,那就太酷了)。

Collection=[]
def get_url_data(url):

    try:
        r = requests.get(url, timeout=10)
        r.raise_for_status()

    except HTTPError:
        return None

    site = bs4.BeautifulSoup(r.text)
    groups=site.select('div.filters')
    word=url.split("/")[-1]

    B=[]
    for x in groups:
        B.append(word)
        T=[a.get_text() for a in x.select('div.blahblah [class=txt]')]
        A1=[a.get_text() for a in site.select('div.blah [class=txt]')]
        if len(T)==1 and len(A1)>0 and T[0]=='verb' and A1[0]!='as in':
            B.append(T)
            B.append([a.get_text() for a in x.select('div.blahblah [class=ttl]')])
            B.append([a.get_text() for a in x.select('div.blah [class=text]')])
            Collection.append(B)
        B=[]

for url in urllist:
    get_url_data(url)
Run Code Online (Sandbox Code Playgroud)

我认为主要的错误代码是这个,它触发了其他错误,因为有一堆以During handling of the above exception, another exception occurred.

Traceback (most recent call last):
  File "C:\Python34\lib\site-packages\requests\packages\urllib3\connectionpool.py", line 319, in _make_request
    httplib_response = conn.getresponse(buffering=True)
TypeError: getresponse() got an unexpected keyword argument 'buffering'
Run Code Online (Sandbox Code Playgroud)

sal*_*hed 5

你可以让你的try-catch块看起来像这样,

try:
    r = requests.get(url, timeout=10)
    r.raise_for_status()

except Exception:
    return
Run Code Online (Sandbox Code Playgroud)

该类Exception将处理所有错误和异常。

如果您想获取异常消息,您可以在except块中打印它。然后,您必须先实例化异常,然后再引发异常。

except Exception as e:
    print(e.message)
    return
Run Code Online (Sandbox Code Playgroud)