如何将Chrome浏览器与Chrome驱动程序分离(Selenium Web Driver C#)

7
我希望使用Selenium Web Driver在VS 2010 C#中打开Chrome浏览器,导航到某个网页,然后关闭驱动程序但保持浏览器打开。我意识到之后需要手动关闭浏览器,这对我来说没问题。
到目前为止,我已经:
DriverService service = ChromeDriverService.CreateDefaultService();
ChromeOptions options = new ChromeOptions();
options.AddAdditionalCapability("chrome.detach",true);
m_driver = new ChromeDriver(service, options, TimeSpan.FromMilliseconds(1000));
[m_driver does stuff like navigate page, double click stuff, etc]
[last line: try to close driver but not browser]

我已经尝试了以下所有内容作为最后一行:

m_driver.Dispose(); // closes both browser and driver

m_driver.Close(); //closes just the browser and not the driver

m_driver.Quit(); // closes both browser and driver

service.Dispose(); // closes both browser and driver

有什么想法吗?
5个回答

2
我们可以使用“detach”选项从chromedriver分离chrome实例。
示例代码:
ChromeDriverService cdservice = new ChromeDriverService.Builder()
                .usingDriverExecutable(new File("/path/to/chromedriver.exe"))
                .withLogFile(new File("/path/to/chromedriver.log"))
                .usingAnyFreePort().withVerbose(true).build();
cdservice.start();
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("detach", true);
ChromeDriver driver = new ChromeDriver(cdservice,options);
driver.manage().timeouts().implicitlyWait(1, TimeUnit.MINUTES);
driver.get("http://www.google.com/");

// Do not call driver.quit().. instead stop chromedriver service.
cdservice.stop();

我正在使用 Selenium.WebDriver 版本 2.48。"options.setExperimentalOption" 不存在。另外,你确定那是 C# 吗? - Jay Sullivan

0

在C#中至少有以下几行代码可以实现:

driverOptions.AddExcludedArgument("enable-automation");
driverOptions.AddAdditionalCapability("useAutomationExtension", false);

0

这是不可能的,那种分离根本不存在。


那么为什么ChromeDriver网站上有相关文档呢?- https://sites.google.com/a/chromium.org/chromedriver/capabilities(请参见“detach”) - Jay Sullivan
1
@JaySullivan 因为这个答案是在ChromeDriver刚出来时给出的,当时它无法支持该功能(可能现在是唯一支持该功能的答案)。 - Arran
3
有趣的是,尽管ChromeDrive文档中有记录,我已经测试了“detach”但并没有起作用。很难说我是不是做错了——到目前为止,我还没有看到其他任何人声称成功的情况。 - Jay Sullivan

0

chromeservice.driver.close()

这在过去对我有效,但在这种情况下,您可能需要为方法编写一些代码。


也许您可以添加一些编程建议的代码片段。 - Olimpiu POP

0
(Python)当我调用selenium.get()函数时,Chrome会打开并在短时间内关闭。我在网上找到了以下代码来解决这个问题:它适用于我在Python3中使用的MacOSX 12.3 Monterey和Chrome版本105.0.5195.102。
从selenium导入webdriver 选项= webdriver.ChromeOptions()
选项.add_experimental_option("detach", True)
driver = webdriver.Chrome(chrome_options=options, executable_path='/Users//.wdm/drivers/chromedriver/mac64/105.0.5195/chromedriver')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接