You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium+pytest多次访问同一URL报invalid session id错误求助

问题根因
  • 你使用的pytest fixture scope配置为class,整个测试类运行周期内只会初始化1次driver实例,对应唯一的浏览器会话
  • driver.close()的作用是关闭当前激活的浏览器标签页,当浏览器仅存在1个标签页时,执行该方法会直接退出浏览器进程,关联的会话ID会被同步销毁,后续复用已销毁会话对应的driver实例发起请求,就会抛出selenium.common.exceptions.InvalidSessionIdException报错
修复方案

你可以根据自己的测试需求选择以下任意一种方案:

方案1:复用现有driver会话,删除多余的close操作

如果允许在同一会话下统计三次加载时间,直接删除测试用例中所有的self.driver.close()语句,同时在fixture的yield语句后添加统一销毁会话的逻辑即可,修改后代码如下:

fixture修改示例

@pytest.fixture(scope='class')
def setupone(request):
  browser = request.config.getoption("browser_name")
  env_name = request.config.getoption("env")
  product = request.config.getoption("product_name")
  dict = getData(product)
  if browser == "PerfChrome" and env_name == "Production":
      options = webdriver.ChromeOptions()
      options.add_argument('disable-infobars')
      capabilities = DesiredCapabilities.CHROME
      capabilities['goog:loggingPrefs'] = {"performance": "ALL"}
      driver = SeleneDriver.wrap(webdriver.Chrome(desired_capabilities=capabilities, 
    executable_path=ChromeDriverManager().install(), chrome_options=options))
    request.cls.product = product
    request.cls.driver = driver
    yield
    # 新增会话销毁逻辑
    driver.quit()

如果需要避免缓存对性能统计结果的干扰,可以在每次调用driver.get()前添加driver.delete_all_cookies()清除缓存。

方案2:每次统计都使用全新会话

如果要求三次加载统计都在全新的独立会话下执行,做以下两处修改:

  1. 将fixture的scope从class修改为function,每次执行测试函数前都会重新初始化driver
  2. 把原来单测试函数内的三次访问逻辑,拆分为三个独立的测试函数,或者在测试函数内每次统计完成后执行driver.quit(),再手动重新初始化driver实例

方案3:保留close操作,适配会话不销毁

如果必须每次统计后关闭当前页面,可以通过多标签切换的方式执行close,保留driver会话有效性,替换原self.driver.close()的代码为以下逻辑:

# 新开空白标签页
self.driver.execute_script("window.open('');")
# 切换到加载完页面的旧标签页
self.driver.switch_to.window(self.driver.window_handles[0])
# 关闭旧标签页
self.driver.close()
# 切换回新的空白标签页,等待下次访问
self.driver.switch_to.window(self.driver.window_handles[0])

内容的提问来源于stack exchange,提问作者HARSHAL WARKAR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 05:27:03