Search code examples
seleniumselenium-webdriverproxywebdriverhttp-proxy

Selenium Proxy IP Address Configuration IP Not Correct


I have paid/rented a proxy server in brazil

String proxyAddress = "myusername:myuserpass123@196.18.199.51:15464"
proxy.setAutodetect(false);
proxy.setHttpProxy(proxyAddress);
proxy.setSslProxy(proxyAddress);
chromeOptions.setCapability(CapabilityType.PROXY, proxy);
WebDriver webDriver = new ChromeDriver(chromeOptions);

I m running the webdriver on my local computer and I am in Indonesia. When the chrome browser opens up, I can debug and made sure that capabilities were set correctly: I can see the manual proxy setting set to the correct address string above. However, when webdriver opens https://api.ipify.org/?format=json, it still returns my IP in Indonesia. What am I Missing here? My expectation is because I had configured webdriver to be proxied by a server in Brazil, https://api.ipify.org/?format=json should return Brazilian IP address?


Solution

  • Using Selenium 4 BiDirectional API (https://www.selenium.dev/documentation/webdriver/bidirectional/bidi_api/)

    Register Basic Auth. Some applications make use of browser authentication to secure pages. With Selenium, you can automate the input of basic auth credentials whenever they arise.

    //C#
    //Console App .NET 6
    
    using OpenQA.Selenium;
    using OpenQA.Selenium.Chrome;
    
    Proxy proxy = new Proxy();
    var proxyAddress = "address:port";
    proxy.HttpProxy = proxyAddress;
    proxy.SslProxy = proxyAddress;
    
    ChromeOptions options = new ChromeOptions();
    options.Proxy = proxy;
    
    IWebDriver driver = new ChromeDriver(options);
    
    NetworkAuthenticationHandler handler = new NetworkAuthenticationHandler()
    {
        UriMatcher = (d) => d.Host.Contains("your-domain.com"), // or set it `true` to enable proxy everywhere
        Credentials = new PasswordCredentials("admin", "password")
    };
    
    INetwork networkInterceptor = driver.Manage().Network;
    networkInterceptor.AddAuthenticationHandler(handler);
    await networkInterceptor.StartMonitoring();
    
    driver.Navigate().GoToUrl("https://api.ipify.org/?format=json");
    
    await networkInterceptor.StopMonitoring();