如何使用 Chrome 驱动程序版本 83.0.4103.39 和 Selenium 使用 user-data-dir 标志启动 Chrome headless

How to start Chrome headless with user-data-dir flag with ChromeDriver version 83.0.4103.39 and Selenium

代码

ChromeOptions options = new ChromeOptions();

options.AddArguments("--headless");
options.AddArguments("--disable-gpu");
options.AddArguments("--disable-software-rasterizer");
options.AddArguments("--user-data-dir=/profiles/" + profile);
options.AddArguments("--disable-software-rasterizer");
options.AddArguments("--window-size=1920x1080");
options.AddArguments("--disable-extensions");
options.AddArguments("--disable-plugins-discovery");

IWebDriver webDriver = new ChromeDriver(options);
WebDriverWait wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(15));
webDriver.Navigate().GoToUrl(@"someUrl"); ---> Here code stucks

错误:

OpenQA.Selenium.WebDriverException: 'The HTTP request to the remote WebDriver server for URL http://localhost:64225/session timed out after 60 seconds.'

我也试过了

options.AddArguments("--disable-dev-shm-usage");
options.AddArguments("--no-sandbox");

控制台输出

"A cookie associated with a cross-site resource at 
<SomeSite> was set without the `SameSite` attribute. 
A future release of Chrome will only deliver cookies 
with cross-site requests if they are set with 
`SameSite=None` and `Secure`. You can review cookies 
in developer tools under Application>Storage>Cookies 
and see more details at 
https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.", 
source: <someURL> (0)

这个错误信息...

OpenQA.Selenium.WebDriverException: 'The HTTP request to the remote WebDriver server for URL http://localhost:64225/session timed out after 60 seconds.

...暗示 ChromeDriver 无法 initiate/spawn 新的 Browsing ContextChrome 浏览器 会话使用所需 Chrome Profile.

根据 How to open a Chrome Profile through --user-data-dir argument of Selenium 中的讨论,不是仅通过 user-data-dir 指定 目录 名称,您需要传递 绝对user-data-dir.

的路径

解决方案

所以你需要替换这行代码:

options.add_argument("user-data-dir=bot_data")

有:

options.add_argument("user-data-dir=C:\Users\AtechM_03\AppData\Local\Google\Chrome\User Data\bot_data")

参考

您可以在以下位置找到一些相关讨论:


结尾

一些相关文档: