我在我的应用程序中使用 Chrome、Firefox 和 Edge 的驱动程序,但总是遇到同样的问题。 因此,在这篇文章中,我以 Chrome 驱动程序为例减少了我的请求。
需要什么:
这是一个页面,向我们展示了 Chrome 驱动程序类及其选项: https://www.selenium.dev/selenium/docs/api/dotnet/html/T_OpenQA_Selenium_Chrome_ChromeDriver.htm
但是我需要的3个积分没有一起列出。
这是我的代码片段和推荐:
string str_DriverPath = @"C:\_MT5_TOOLS\DRIVER\CHROME";
// hide Console
ChromeDriverService service = ChromeDriverService.CreateDefaultService();
service.HideCommandPromptWindow = true;
//// change Standard-Download-Path
ChromeOptions options = new ChromeOptions();
var downloadDirectory = GlobalVars.RootPath + @"Pool\" + GlobalVars.strSymbol + @"\" + GlobalVars.strSymbol + @"_" + GlobalVars.strPeriod;
options.AddUserProfilePreference("download.default_directory", downloadDirectory);
options.AddUserProfilePreference("download.prompt_for_download", false);
options.AddUserProfilePreference("disable-popup-blocking", "true");
// Start Driver:
//webdriver = new ChromeDriver(service, options); // works fine
//webdriver = new ChromeDriver(str_DriverPath, options); // works fine
webdriver = new ChromeDriver(str_DriverPath, service, options); // will not work
如何将我的 3 点合并为一个驱动程序?
在尝试了围绕环境变量“PATH”设置驱动程序路径的所有可能方法后,在 2022 年似乎是不可能的。 从手动到编码,这对我来说仍然不起作用! 也许这是过去的一个伎俩......
解决方案:
在另一个门户网站上,我发现了一个非常好的且简单的工作解决方案! 下面代码中的第二行就达到了这个目的。 它只是服务,可以将驱动程序的 PATH 放置在其中。 这对于 Edge、Chrome 和 Firefox 来说是相同的。
// DriverService with Path to driver.exe
ChromeDriverService service = ChromeDriverService.CreateDefaultService(@"C:\_MT5_TOOLS\DRIVER\CHROME");
// hide driver Console? true/false
service.HideCommandPromptWindow = true;
// change Standard-Download-Path
ChromeOptions options = new ChromeOptions();
var downloadDirectory = GlobalVars.RootPath + @"Pool\" + GlobalVars.strSymbol + @"\" + GlobalVars.strSymbol + @"_" + GlobalVars.strPeriod;
options.AddUserProfilePreference("download.default_directory", downloadDirectory);
options.AddUserProfilePreference("download.prompt_for_download", false);
options.AddUserProfilePreference("disable-popup-blocking", "true");
// Selenium Driver starten:
webdriver = new ChromeDriver(service, options);
// C# Windows
string path = @"c:\websites\test\selenium\chrome\";
opt.BinaryLocation = path + "chrome.exe";
driver = new ChromeDriver(path, opt);