業務需要購買http隧道,發現阿布雲還行,使用Selenium本來想要用谷歌瀏覽器的,但是發現不能直接設置賬號,所以選用火狐。
按照官方JAVA示例的改編,其中WebDriver實例化不能直接添加FirefoxProfile,所以需要創建一個FirefoxOtions,在這里面添加Profile。
有一個要注意的是,需要引用System.Text.Encoding.CodePages的NuGet包,否則會找不到 Encoding(437) 錯誤。
參考這個:https://github.com/SeleniumHQ/selenium/issues/4816
代碼如下:
//必須添加這個代碼,否則使用Profile報錯
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); FirefoxProfile profile = new FirefoxProfile(); // 使用代理 profile.SetPreference("network.proxy.type", 1); // 代理服務器配置 ProxyHost-http-dyn.abuyun.com ProxyPort-9020 profile.SetPreference("network.proxy.http", GlobalConf.ProxyHost); profile.SetPreference("network.proxy.http_port", GlobalConf.ProxyPort); profile.SetPreference("network.proxy.ssl", GlobalConf.ProxyHost); profile.SetPreference("network.proxy.ssl_port", GlobalConf.ProxyPort);
//ProxyUser-通行證書 ProxyPass-通行密鑰 profile.SetPreference("username", GlobalConf.ProxyUser); profile.SetPreference("password", GlobalConf.ProxyPass); // 所有協議公用一種代理配置,如果單獨配置,這項設置為false profile.SetPreference("network.proxy.share_proxy_settings", true); // 對於localhost的不用代理,這里必須要配置,否則無法和webdriver通訊 profile.SetPreference("network.proxy.no_proxies_on", "localhost"); // 以代理方式啟動firefox FirefoxOptions opt = new FirefoxOptions(); opt.Profile = profile; _firefoxDriver = new FirefoxDriver(GlobalConf.BrowserPath, opt);