You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python/Selenium中处理NoSuchElementException并填充默认值

解决方法

问题出在你except块里的raise语句——你捕获异常后又把它重新抛出去了,这就导致脚本还是会终止,根本没机会执行填充默认值的逻辑。

修改步骤:

  • 删掉except块里的raise
  • 在except块里给score赋值默认值(比如"No Value")

修改后的file_1.py代码示例:

def getAttributes(self):
    # ... 其他代码 ...
    try: 
        score = box.find_element(By.CLASS_NAME, 'dealClass').get_attribute('innerHTML').strip()  
        if not score:
            raise NoSuchElementException(f"Score does not currently exist for {name}, as of {datetime.today()}") 
    except NoSuchElementException as e: 
        print('Exception is: ', e)
        # 这里设置默认值
        score = "No Value"
    # ... 把score加入要返回的行数据中 ...

另外注意file_2.py里的小错误:report = ReportSearchResults)多了一个右括号,应该改成report = ReportSearchResults(),否则会先触发语法错误。

这样修改后,不管是元素找不到还是元素内容为空,都会把score设为默认值,脚本不会终止,能正常完成表格填充。

内容的提问来源于stack exchange,提问作者hal9kaye

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 06:30:37