Selenium遍历URL列表遇到离线网站时如何继续执行后续操作
Selenium遍历URL超时跳过方案修复
问题原因
代码遇到离线站点直接停止运行,核心是两个问题:
- 触发
TimeoutException后没有终止当前页面的挂起加载状态,driver实例状态异常会导致后续请求直接抛出未捕获错误,终止程序 - 仅捕获了超时异常,未覆盖站点可访问但元素找不到、点击失败等其他异常场景,这类异常也会直接打断循环
修复后的代码
from selenium import webdriver import time from selenium.common.exceptions import TimeoutException, NoSuchElementException # 新版本Selenium需要导入By来定位元素,旧版本可以忽略 from selenium.webdriver.common.by import By driver = webdriver.Chrome() MAX_TIMEOUT_SECONDS = 60 urlsList = ['urlone','urltwo', 'urlthree', 'urlfour'] for s in urlsList: url = str(s) try: driver.set_page_load_timeout(MAX_TIMEOUT_SECONDS) driver.get(url) # 旧版本Selenium可以保留原find_element_by_xpath写法 systemTab = driver.find_element(By.XPATH, '/html/body/ul[1]/li[3]/a') systemTab.click() buttonRaul = driver.find_element(By.XPATH, '/html/body/ul[2]/li[4]/a') buttonRaul.click() buttomGoo = driver.find_element(By.XPATH, '/html/body/div[2]/div[2]/button') buttomGoo.click() time.sleep(5) except TimeoutException: # 超时后终止当前页面加载,重置driver状态 driver.execute_script("window.stop();") # 可选清理站点cookie,避免不同站点会话冲突 driver.delete_all_cookies() continue except (NoSuchElementException, Exception): # 覆盖元素找不到、点击失败等其他异常,避免程序终止 # 如需排查问题可新增日志打印,例如print(f"处理{url}失败:{e}") continue driver.quit()
可选优化项
如果要进一步提升稳定性,可以把固定的time.sleep替换为Selenium的显式等待,指定元素最长等待时间,避免页面渲染慢导致的元素查找失败。
内容的提问来源于stack exchange,提问作者Rararaul
相关产品推荐
相关产品推荐

