Selenium Python设置page_load_timeout后超时报错,如何让循环正常执行?
问题分析与解决方案
问题根源
你的代码中TimeoutException未被有效捕获,导致循环中断,主要原因有两个:
- 页面加载超时的异常并非在
search_action的try块内抛出,而是来自循环中调用的se.get_domain(domain)(该方法内部应该是执行了driver.get()),这部分操作没有被异常捕获。 set_page_load_timeout每次在search_action中重复设置不是最优方案,且未覆盖所有页面加载场景。
修复后的代码示例
1. 完善类的初始化与get_domain方法
from selenium.common.exceptions import TimeoutException, NoSuchElementException from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys class class_name: def __init__(self): self.driver = webdriver.Chrome() # 按实际使用的驱动调整 self.driver.set_page_load_timeout(1) # 全局统一设置页面加载超时时间 def get_domain(self, domain): try: self.driver.get(domain) except TimeoutException as e: print(f"域名 {domain} 加载超时: {e}") # 强制停止页面加载,避免驱动阻塞 self.driver.execute_script("window.stop();") def search_action(self, xpath, value): try: element = self.driver.find_element(By.XPATH, xpath) element.send_keys(value) element.send_keys(Keys.ENTER) except TimeoutException as e: print(f"搜索操作超时: {e}") self.driver.execute_script("window.stop();") except NoSuchElementException as e: print(f"未找到目标元素: {e}") print('success')
2. 循环执行部分(保持原有逻辑)
se = class_name() for domain in config['list_domain']: se.get_domain(domain) for i in range(1, 100): xpath = config[domain]['list_test']['search'] se.search_action(xpath, i) se.get_domain(domain)
关键修复点
- 所有触发页面加载的操作(
driver.get、提交表单后的跳转)都用try-except包裹,确保TimeoutException被捕获。 - 页面超时后执行
window.stop(),强制终止加载,避免驱动处于阻塞状态影响后续循环。 - 全局统一设置页面加载超时,无需重复配置。
- 额外捕获
NoSuchElementException等常见异常,防止其他意外错误中断循环。
内容的提问来源于stack exchange,提问作者Từ Phan
相关产品推荐
相关产品推荐

