如何重启Selenium Grid中异常退出的WebDriver以维持16个可用实例?
解决方案
核心问题分析
你的代码主要问题出在失效Driver的替换逻辑错误和Driver管理混乱:
- 仅将新Driver追加到
drivers_list,但失效Driver仍留在列表中,get_driver()仍可能拿到无效实例 - 异常处理后重复执行
driver.get(current_link),易引发二次错误 - 新Driver的无头模式配置未正确传递,导致未按预期运行
修复后的代码实现
1. 提前配置Firefox无头模式参数
先把无头模式、窗口尺寸等配置整合到Options中,避免创建Driver后重复设置:
from selenium.webdriver.firefox.options import Options firefox_options = Options() firefox_options.add_argument("--headless") firefox_options.add_argument("--window-size=1366,784")
2. 修改Driver异常处理与替换逻辑
核心是移除失效Driver,再补充新Driver,确保drivers_list中始终是可用实例:
while executed_website_count != len(list_of_websites): driver = get_driver() current_link = get_link() # 轻量验证Driver会话是否存活 is_alive = True try: driver.current_url except (InvalidSessionIdException, WebDriverException): is_alive = False if not is_alive: # 从列表移除失效Driver if driver in drivers_list: drivers_list.remove(driver) # 创建新Driver并加入列表 new_driver = webdriver.Remote( command_executor='http://localhost:4444', options=firefox_options ) drivers_list.append(new_driver) driver = new_driver # 执行任务逻辑 try: driver.get(current_link) # ...此处编写后续操作代码... executed_website_count += 1 except Exception as e: print(f"处理链接{current_link}出错: {str(e)}") # 若任务执行中Driver失效,立即移除 try: driver.current_url except: if driver in drivers_list: drivers_list.remove(driver)
3. 优化get_driver()函数
确保该函数能返回真正可用的Driver,而非随机选取:
def get_driver(): # 遍历列表,返回第一个存活的Driver for driver in drivers_list: try: driver.current_url return driver except: continue # 无可用Driver时直接创建新实例补充 new_driver = webdriver.Remote( command_executor='http://localhost:4444', options=firefox_options ) drivers_list.append(new_driver) return new_driver
额外注意事项
- 定期清理失效Driver:可在循环间隙加入批量清理逻辑,移除所有无法连接的实例,避免列表冗余
- 监控Grid状态:通过
http://localhost:4444/status查看Grid节点和会话状态,确认新Driver是否成功注册 - 任务去重:确保
get_link()不会返回已处理的链接,避免重复执行任务
内容的提问来源于stack exchange,提问作者priyanshuraj400
相关产品推荐
相关产品推荐

