一尘不染

如何使用Selenium Webdriver .NET绑定设置Chrome偏好设置?

selenium

这是我正在使用的,可以成功设置用户代理,而无法下载首选项。

Windows 7,Chrome 26,Selenium-dotnet-2.31.2,chromedriver_win_26.0.1383.0

ChromeOptions chromeOptions = new ChromeOptions();
var prefs = new Dictionary<string, object> {
    { "download.default_directory", @"C:\code" },
    { "download.prompt_for_download", false }
};
chromeOptions.AddAdditionalCapability("chrome.prefs", prefs);
chromeOptions.AddArgument("--user-agent=" + "some safari agent");
var driver = new ChromeDriver(chromeOptions);

取自chromedriver.log:

[1.201][FINE]:      Initializing session with capabilities {

   "browserName": "chrome",

   "chrome.prefs": {

      "download.default_directory": "C:\\code",

      "download.prompt_for_download": false

   },

   "chrome.switches": [ "--user-agent=Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.57.2 (KHTML, like Gecko) Version..." ],

   "chromeOptions": {

      "args": [ "--user-agent=Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.57.2 (KHTML, like Gecko) Version..." ],

      "binary": "",

      "extensions": [  ]

   },

   "javascriptEnabled": true,

   "platform": "WINDOWS",

   "version": ""

}

检查临时首选项文件,位于*temp\Google\Chrome\User Data\Default\Preferences,否,"default_directory""prompt_for_download"已设置。

   "download": {
      "directory_upgrade": true
   },

阅读 243

收藏
2020-06-26

共1个答案

一尘不染

Selenium
dotNet驱动程序不支持chrome.prefs开箱即用。问题在于chrome.prefs必须prefschromeOptions节点下进行定义。本ChromeOptions类不包含这个变量,所以您需要创建自己ChromeOptions的类:

public class ChromeOptionsWithPrefs: ChromeOptions
{
    public Dictionary<string,object> prefs { get; set; }
}

public static void Initialize()
{
    var options = new ChromeOptionsWithPrefs();
    options.prefs = new Dictionary<string, object>
    {
        { "intl.accept_languages", "nl" }
    };
    _driver = new ChromeDriver(@"C:\path\chromedriver", options);
}
2020-06-26