Setting a proxy for Chrome Driver in Selenium

前端 未结 3 1097
情歌与酒
情歌与酒 2020-12-03 11:05

I am using Selenium Webdriver using C# for Automation in Chrome browser. I need to check if my webpage is bloced in Some regions(some ip ranges). So I have to set a proxy in

3条回答
  •  时光取名叫无心
    2020-12-03 11:49

    Please Following code, this will help you to change the proxy

    First create chrome extension and paste the following java script code.

    Java Script Code

    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# Code

        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/");
    

提交回复
热议问题