在Selenium中为Chrome驱动程序设置代理

我在Chrome浏览器中使用C#for Automation的Selenium Webdriver。 我需要检查我的网页是否在某些地区(某些IP范围)中出现了问题。 所以我必须在Chrome浏览器中设置代理。 我尝试了下面的代码。 代理正在设置但我收到错误。 有人可以帮助我。

ChromeOptions options = new ChromeOptions(); options.AddArguments("--proxy-server=XXX.XXX.XXX.XXX"); IWebDriver Driver = new ChromeDriver(options); Driver.Navigate().GoToUrl("myUrlGoesHere"); 

当我运行此代码时,我在Chrome浏览器中收到以下消息:我尝试启用“代理”选项,但“禁用更改代理设置”选项。

*无法连接到代理服务器

代理服务器是充当计算机与其他服务器之间的中介的服务器。 目前,您的系统已配置为使用代理,但Google Chrome无法连接到该代理。 如果使用代理服务器…请检查代理设置或联系网络管理员以确保代理服务器正常工作。 如果您认为自己不应该使用代理服务器:转到Chrome菜单>设置>显示高级设置…>更改代理设置…> LAN设置,然后取消选择“为LAN使用代理服务器”。 错误代码:ERR_PROXY_CONNECTION_FAILED *

我正在使用Selenium 2.50.1的nuget包:

 ChromeOptions options = new ChromeOptions(); proxy = new Proxy(); proxy.Kind = ProxyKind.Manual; proxy.IsAutoDetect = false; proxy.HttpProxy = proxy.SslProxy = "127.0.0.1:3330"; options.Proxy = proxy; options.AddArgument("ignore-certificate-errors"); var chromedriver = new ChromeDriver(options); 

如果您的代理需要用户登录,您可以使用登录用户/密码详细信息设置代理,如下所示:

 options.AddArguments("--proxy-server=http://user:password@yourProxyServer.com:8080"); 

请关注代码,这将帮助您更改代理

首先创建chrome扩展并粘贴以下java脚本代码。

Java脚本代码

 var Global = { currentProxyAouth: { username: '', password: '' } } var userString = navigator.userAgent.split('$PC$'); if (userString.length > 1) { var credential = userString[1]; var userInfo = credential.split(':'); if (userInfo.length > 1) { Global.currentProxyAouth = { username: userInfo[0], password: userInfo[1] } } } chrome.webRequest.onAuthRequired.addListener( function(details, callbackFn) { console.log('onAuthRequired >>>: ', details, callbackFn); callbackFn({ authCredentials: Global.currentProxyAouth }); }, { urls: [""] }, ["asyncBlocking"]); chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { console.log('Background recieved a message: ', request); POPUP_PARAMS = {}; if (request.command && requestHandler[request.command]) requestHandler[request.command](request); } ); 

C#代码

  var cService = ChromeDriverService.CreateDefaultService(); cService.HideCommandPromptWindow = true; var options = new ChromeOptions(); options.AddArguments("--proxy-server=" + "<< IP Address >>" + ":" + "<< Port Number >>"); options.AddExtension(@"C:\My Folder\ProxyChanger.crx"); options.Proxy = null; string userAgent = "<< User Agent Text >>"; options.AddArgument($"--user-agent={userAgent}$PC${"<< User Name >>" + ":" + "<< Password >>"}"); IWebDriver _webDriver = new ChromeDriver(cService, options); _webDriver.Navigate().GoToUrl("https://whatismyipaddress.com/");