python - 如何忽略NameError并继续运行程序的其余部分?

标签 python web-scraping error-handling

我使用的代码偶尔会起作用,但是我一直需要一些东西来工作。我正在抓取的网站有时会显示信息,而其他时候却忽略了它,这就是为什么我在运行程序后收到错误消息。由于网站并不总是为某些事件发布时间,因此显然未定义“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

最佳答案

而不是抑制异常

with suppress(Exception): 
    event_time = s.select_one('.time').text.strip() 
捕获它并添加默认值
try:
    event_time = s.select_con('.time').text.strip()
except Exception:
    event_time = ''
捕获一般异常可以隐藏其他错误。最好找出可能发生的异常并将其捕获。

关于python - 如何忽略NameError并继续运行程序的其余部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63401509/

相关文章:

python - 反转大型 JSON 字典

python - 2016 年 Pandas 数据框用户数量最多

python - Django ImageField 不会在网页上显示

javascript - 如何在 Cheerio 中执行索引以进行网页抓取

flutter - 如何解决Build失败并出现异常?

ruby-on-rails - Ruby on Rails Flash 现在出现多个错误

python - 将带有标题和编码问题的文件读入 numpy 数组

python - BeautifulSoup 不适用于某些网站

python - 如何从其他网站获取数据?

mysql - 在 JSON_EXTRACT 中返回空值