Selenium WebDriver C#出现invalid session id错误求助
解决Selenium的"invalid session id"错误
你遇到的OpenQA.Selenium.WebDriverException: invalid session id错误,根源很明确:在Process_Login_Test方法的最后一行调用了Variables_RW.driver.Close(),这直接关闭了当前浏览器会话,导致后续Process_Cotizacion_Contado_Test里再使用同一个Variables_RW.driver对象时,会话已经失效,自然就触发了无效会话ID的错误。
另外还有一个潜在问题:你的Process_Login和Process_Cotizacion_Contado两个测试类都有[ClassInitialize]方法,这会导致每次运行测试类时都重新创建ChromeDriver实例,可能引发资源冲突。
具体修复方案:
移除登录方法中的关闭浏览器代码
删掉Process_Login_Test末尾的Variables_RW.driver.Close(),因为登录是报价流程的前置步骤,不能在这里关闭会话。统一管理Driver的生命周期
只在主测试类(比如Process_Cotizacion_Contado)中初始化和清理Driver,避免多个测试类重复创建实例。如果需要复用登录逻辑,把登录方法改成普通的公共方法,而不是标记为[TestMethod](因为[TestMethod]会被测试框架单独执行,而不是作为其他测试的步骤)。
修改后的代码示例:
登录模块(改为工具类,去掉TestClass标记)
using System; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Microsoft.VisualStudio.TestTools.UnitTesting; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Support.UI; using Gmg.Rapiweb.Selenium.Test.Variables; using System.Drawing.Imaging; namespace Gmg.Rapiweb.Selenium.Test.Processes.RW_CR { // 去掉[TestClass],把登录作为公共方法 public class LoginHelper { private Helpers helpers = new Helpers(); // 改为普通公共方法,供其他测试调用 public void PerformLogin() { //Maximiza el navegador Variables_RW.driver.Manage().Window.Maximize(); //Entra a la url Variables_RW.driver.Navigate().GoToUrl(Variables_RW.url); //LLena espacios del incio de sesión SelectElement spais = new SelectElement(Variables_RW.driver.FindElement(By.XPath("//SELECT[@id='pais']"))); spais.SelectByText("Costa Rica"); Variables_RW.driver.FindElement(By.Id("user")).Click(); Variables_RW.driver.FindElement(By.Id("user")).Clear(); Variables_RW.driver.FindElement(By.Id("user")).SendKeys(Variables_RW.usuario); Variables_RW.driver.FindElement(By.Id("password")).Click(); Variables_RW.driver.FindElement(By.Id("password")).Clear(); Variables_RW.driver.FindElement(By.Id("password")).SendKeys(Variables_RW.password); Screenshot loginImage = ((ITakesScreenshot)Variables_RW.driver).GetScreenshot(); loginImage.SaveAsFile("D://Users/wa5699cr/Documents/Proyectos 2020/Automatización de procesos/RW Pre-producción/Evidencias/Login/login.png", ScreenshotImageFormat.Png); Variables_RW.driver.FindElement(By.Id("btnSignIn")).Click(); helpers.EsperaObjeto(By.XPath("//BUTTON[@id='btnSelect']"), 30, Variables_RW.driver); Thread.Sleep(5 * 1000); //Seleccionar tienda y entrar SelectElement stienda = new SelectElement(Variables_RW.driver.FindElement(By.XPath("//select[@id='tiendas']"))); stienda.SelectByText(Variables_RW.tienda_1); Thread.Sleep(2 * 1000); Screenshot loginImage1 = ((ITakesScreenshot)Variables_RW.driver).GetScreenshot(); loginImage1.SaveAsFile("D://Users/wa5699cr/Documents/Proyectos 2020/Automatización de procesos/RW Pre-producción/Evidencias/Login/login1.png", ScreenshotImageFormat.Png); Variables_RW.driver.FindElement(By.XPath("//BUTTON[@id='btnSelect']")).Click(); helpers.EsperaObjeto(By.XPath("(//A[@class='btn btn-lg btnInicio'])[2]"), 12, Variables_RW.driver); Thread.Sleep(2 * 1000); // 移除这一行:Variables_RW.driver.Close(); } } }
报价流程模块(统一管理Driver生命周期)
using System; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Microsoft.VisualStudio.TestTools.UnitTesting; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Support.UI; using Gmg.Rapiweb.Selenium.Test.Variables; using System.Drawing.Imaging; using System.Security.Cryptography.X509Certificates; using System.Collections.Generic; namespace Gmg.Rapiweb.Selenium.Test.Processes.RW_CR { [TestClass] public class Process_Cotizacion_Contado { private StringBuilder verificationErrors; private static string baseURL; private bool acceptNextAlert = true; Helpers helpers = new Helpers(); private string cedula = "11-1111-1111"; [ClassInitialize] public static void InitializeClass(TestContext testContext) { Variables_RW.driver = new ChromeDriver(); baseURL = "https://www.google.com/"; } [ClassCleanup] public static void CleanupClass() { try { Variables_RW.driver.Quit(); // 使用Quit()彻底关闭浏览器和会话 Variables_RW.driver.Dispose(); } catch (Exception) { // Ignore errors if unable to close the browser } } [TestInitialize] public void InitializeTest() { verificationErrors = new StringBuilder(); } [TestCleanup] public void CleanupTest() { Assert.AreEqual("", verificationErrors.ToString()); } [TestMethod] public void Process_Cotizacion_Contado_Test() { LoginHelper loginHelper = new LoginHelper(); loginHelper.PerformLogin(); // 调用登录工具方法 try { Variables_RW.driver.FindElement(By.XPath("(//A[@class='btn btn-lg btnInicio'])[2]")).Click(); helpers.VisualizaObjeto(By.XPath("//P[text()='Cargando cotizador... Espere por favor...']"), 10, Variables_RW.driver); helpers.EsperaCargar(3); helpers.EsperaObjeto(By.XPath("//BUTTON[@id='btnMenuHeader2LineaNuevaCotizacion']"), 5, Variables_RW.driver); helpers.EsperaCargar(5); Screenshot CotizacionContado = ((ITakesScreenshot)Variables_RW.driver).GetScreenshot(); CotizacionContado.SaveAsFile("D://Users/wa5699cr/Documents/Proyectos 2020/Automatización de procesos/RW Pre-producción/Evidencias/Cotización/Contado/cotización1.png", ScreenshotImageFormat.Png); Buscar_Persona(); } catch (Exception ex) { Screenshot CotizacionContado1 = ((ITakesScreenshot)Variables_RW.driver).GetScreenshot(); CotizacionContado1.SaveAsFile("D://Users/wa5699cr/Documents/Proyectos 2020/Automatización de procesos/RW Pre-producción/Evidencias/Cotización/Contado/cotizaciónError1.png", ScreenshotImageFormat.Png); throw ex; } } // 这里补充Buscar_Persona方法的实现(你原代码里没贴出来) private void Buscar_Persona() { // 你的代码逻辑 } } }
额外建议:
- 尽量避免使用
Thread.Sleep(),改用WebDriverWait来等待元素加载,这样更稳定也更高效。 - 确保
Variables_RW类中的driver是静态且唯一的,避免多线程或多测试类之间的冲突。
内容的提问来源于stack exchange,提问作者WALTER JEREMY ABARCA SALAZAR
相关产品推荐
相关产品推荐

