如何在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
相关产品推荐
相关产品推荐

