【问题标题】:How to ignore a NameError and continue running the rest of the program?如何忽略 NameError 并继续运行程序的其余部分?
【发布时间】:2020-08-13 18:52:42
【问题描述】:

我正在使用的代码偶尔可以工作,但我需要一些东西来一直工作。我正在抓取的网站有时会包含信息,而有时会忽略它,这就是我在运行程序后收到错误的原因。由于该网站并不总是发布特定事件的时间,因此显然没有定义“event_time”。

我面临的问题是 with suppress(Exception): 有时有效,有时无效。当网站没有指定时间时,我可以添加什么来跳过 event_time 并让程序继续抓取网站的其余部分?

event_name = s.select_one('.eventname').get_text(strip=True)
event_day = s.select_one('.date').text.strip()
event_month = s.select_one('.month').text.strip()
with suppress(Exception):
    event_time = s.select_one('.time').text.strip()
event_info = s.select_one('.event-header').text.strip()

错误:

NameError
Traceback (most recent call last)
<ipython-input-49-45cf21eb3177> in <module>
     22     print('Dia: ' + event_day)
     23     print('Mes: ' + event_month)
---> 24     print('Hora: ' + event_time)
     25     print('Descripción: ' + event_info)
     26     print('-' * 80)

NameError: name 'event_time' is not defined

【问题讨论】:

    标签: python web-scraping error-handling


    【解决方案1】:

    而不是抑制异常

    with suppress(Exception): 
        event_time = s.select_one('.time').text.strip() 
    

    抓住它并添加一个默认值

    try:
        event_time = s.select_con('.time').text.strip()
    except Exception:
        event_time = ''
    

    捕获一般异常可以隐藏其他错误。最好找出可能发生的异常并捕获这些异常。

    【讨论】:

      【解决方案2】:

      您可以使用 try-except 语句来确保每次都捕获到异常。

      try:
          event_time = s.select_con('.time').text.strip()
      except NameError:
          event_time = ...
      
      
          
          
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-03-17
        • 2010-10-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多