【问题标题】:How to avoid program termination for urllib2.httperror 404 error and display appropriate message如何避免 urllib2.httperror 404 错误导致程序终止并显示适当的消息
【发布时间】:2018-02-21 18:34:33
【问题描述】:

我正在从 10 万个系统 URL(example.com/entry/1 > example.com/entry/100000)中抓取内容。

但是,大约 10% 的 URL 已被删除,这意味着当脚本到达它们时,它会给我错误“urllib2.httperror http 错误 404”并停止运行。

我对 python 比较陌生,想知道是否有办法做这样的事情:

if result == error:
    div_text = "missing"

这样循环可以继续到下一个 URL,但记下它失败了。

【问题讨论】:

    标签: python python-2.7 web-scraping beautifulsoup


    【解决方案1】:

    urllib2.HTTPError 是 Python 引发的异常。您可以使用 try/except 块包装您的 URL 调用:

    try:
        # ... put your URL open call here ... 
    except urllib2.HTTPError:
        div_text = 'missing'
    

    这样,如果再次遇到此异常,Python 解释器将运行该 except 块内的代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-16
      • 1970-01-01
      • 2018-02-22
      • 2017-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-11
      相关资源
      最近更新 更多