Selenium遇异常时如何继续循环?代码问题求助
问题解决:处理元素查找异常时保持循环继续执行
问题描述
原代码需要在open_next()后添加driver.find_element(By.XPATH, '/html/body/table').click(),要求该元素未找到时代码仍能继续执行后续循环。修改后的代码触发异常后会直接跳出整个循环,无法处理剩余的urls。
初始版本代码:
import undetected_chromedriver as uc driver = uc.Chrome() def open_next(): try: driver.get(next(urls)) except StopIteration: return try: for i in range(amount): open_next() button = driver.find_element(By.XPATH, '/html/body/div') driver.execute_script("arguments[0].click();", button) except NoSuchElementException: print('Failed. Try again.') else: pass
修改后出现问题的代码:
import undetected_chromedriver as uc driver = uc.Chrome() def open_next(): try: driver.get(next(urls)) except StopIteration: return try: for i in range(amount): open_next() driver.find_element(By.XPATH, '/html/body/table').click() except NoSuchElementException: button = driver.find_element(By.XPATH, '/html/body/div') driver.execute_script("arguments[0].click();", button) except NoSuchElementException: print('Failed. Try Again.') else: pass
问题原因
- 整个
for循环被包裹在一个大的try块中,一旦某次迭代触发NoSuchElementException,程序会直接跳出循环进入except分支,后续的循环迭代全部终止。 - Python中多个相同类型的
except分支只会匹配第一个,第二个except NoSuchElementException永远不会被执行。
解决方案
将异常捕获逻辑移到循环内部,针对每个元素查找操作单独处理异常,确保单次异常不会中断整个循环。同时注意导入缺失的异常类。
修改后的完整代码:
import undetected_chromedriver as uc from selenium.common.exceptions import NoSuchElementException # 必须导入该异常类 driver = uc.Chrome() def open_next(): try: driver.get(next(urls)) except StopIteration: return for i in range(amount): open_next() # 处理table元素的点击,找不到则跳过 try: driver.find_element(By.XPATH, '/html/body/table').click() except NoSuchElementException: pass # 找不到时不做操作,继续执行后续逻辑 # 处理div按钮的点击,找不到则打印提示 try: button = driver.find_element(By.XPATH, '/html/body/div') driver.execute_script("arguments[0].click();", button) except NoSuchElementException: print('Failed. Try again.')
代码说明
- 将原来的外层
try-except拆分为循环内部的两个独立try-except块,分别处理table和div元素的查找异常。 - 查找table元素失败时,用
pass跳过,继续执行div按钮的点击逻辑。 - 查找div元素失败时,打印提示信息,但不会中断循环,后续的urls仍会被处理。
- 补充导入
NoSuchElementException,避免运行时出现未定义异常的错误。
内容的提问来源于stack exchange,提问作者Andrew
相关产品推荐
相关产品推荐

