使用FirefoxDriver启动Firefox出现空白窗口及NoSuchWindowException问题
解决FirefoxDriver中"Browsing context has been discarded"异常问题
可能原因
- GeckoDriver与Firefox Marionette的会话建立存在延迟,调用
GoToUrl时浏览器上下文未完全初始化 - 临时生成的Firefox配置文件存在加载异常,导致浏览器进程启动但未建立有效会话
- C# Selenium初始化时的超时设置不足以完成Marionette的会话协商
解决步骤
1. 增加初始化后的显式等待
创建FirefoxDriver后,先等待浏览器页面就绪,再执行跳转操作:
string geckoDriverLocationDir = @"C:\dev\geckDriverDir\"; string firefoxFullLocation = @"C:\Program Files\Mozilla Firefox\firefox.exe"; var service = FirefoxDriverService.CreateDefaultService(geckoDriverLocationDir); service.FirefoxBinaryPath = firefoxFullLocation; TimeSpan time = TimeSpan.FromSeconds(15); // 适当延长初始化超时 FirefoxOptions options = new FirefoxOptions(); FirefoxDriver driver = new FirefoxDriver(service, options, time); // 等待页面加载完成,确保上下文就绪 new WebDriverWait(driver, TimeSpan.FromSeconds(15)).Until(d => ((IJavaScriptExecutor)d).ExecuteScript("return document.readyState").ToString() == "complete"); driver.Navigate().GoToUrl("https://youtube.com/");
2. 强制启用Marionette并禁用自动更新
在FirefoxOptions中添加配置,避免自动更新干扰会话,确保Marionette正确启用:
FirefoxOptions options = new FirefoxOptions(); options.AddArgument("--marionette"); // 禁用Firefox自动更新 options.SetPreference("app.update.enabled", false); options.SetPreference("app.update.auto", false); // 禁用默认欢迎页面,减少初始化干扰 options.SetPreference("browser.startup.homepage", "about:blank");
3. 使用自定义Firefox配置文件
避免使用临时配置文件,指定一个预先创建好的本地配置文件:
// 替换为你自己的Firefox自定义配置文件路径 string customProfilePath = @"C:\Users\pusersh\AppData\Roaming\Mozilla\Firefox\Profiles\my-test-profile"; FirefoxOptions options = new FirefoxOptions(); options.Profile = new FirefoxProfile(customProfilePath);
4. 开启GeckoDriver日志排查细节
如果以上方法无效,开启详细日志定位具体错误:
var service = FirefoxDriverService.CreateDefaultService(geckoDriverLocationDir); service.LogLevel = FirefoxDriverLogLevel.Trace; service.LogPath = @"C:\dev\geckodriver_debug.log"; // 指定日志输出路径
内容的提问来源于stack exchange,提问作者Moshe Levi
相关产品推荐
相关产品推荐

