How to set proxy for Chrome browser in selenium using Java code

后端 未结 5 1305
误落风尘
误落风尘 2021-02-08 15:08

I am trying to run my selenium java code to test a webpage. But webpage is not loading because of network restrictions. When I set the proxy manually and hit the url in browser

相关标签:
5条回答
  • DesiredCapabilities dc;
    dc = DesiredCapabilities.chrome();              
    System.setProperty("http.proxyHost", "127.0.0.1");
    System.setProperty("http.proxyPort", "9090");
    System.setProperty("https.proxyHost", "127.0.0.1");
    System.setProperty("https.proxyPort", "9090");                      
    ChromeOptions options = new ChromeOptions();
    options.addArguments("start-maximized");
    options.addArguments("--disable-extensions");
    dc.setCapability(ChromeOptions.CAPABILITY, options);
    driver = new ChromeDriver(dc);
    
    0 讨论(0)
  • 2021-02-08 15:30

    Issue is resolved with below code -

    Proxy proxy = new Proxy(); 
    proxy.setHttpProxy("yoururl:portno"); 
    proxy.setSslProxy("yoururl:portno"); 
    
    DesiredCapabilities capabilities = DesiredCapabilities.chrome(); 
    capabilities.setCapability("proxy", proxy); 
    
    ChromeOptions options = new ChromeOptions(); 
    options.addArguments("start-maximized"); 
    
    capabilities.setCapability(ChromeOptions.CAPABILITY, options); 
    
    driver = new ChromeDriver(capabilities);
    
    0 讨论(0)
  • 2021-02-08 15:30

    Another way of doing it:

            boolean useProxy = true;
            ChromeOptions options = new ChromeOptions().addArguments(
                    '--headless',
                    '--no-sandbox',
                    '--disable-extensions',
                    '--proxy-bypass-list=localhost');
            if (useProxy) {
                options.addArguments("--proxy-server=http://ProxyHost:8080");
            }
    
            WebDriver driver = new ChromeDriver(options);
    

    See https://peter.sh/experiments/chromium-command-line-switches/ for more Chrome switches

    0 讨论(0)
  • 2021-02-08 15:33

    Passing a Capabilities object to the ChromeDriver() constructor is deprecated. One way to use a proxy is this:

    String proxy = "127.0.0.1:5000";
    ChromeOptions options = new ChromeOptions().addArguments("--proxy-server=http://" + proxy);
    WebDriver webDriver = new ChromeDriver(options);
    
    0 讨论(0)
  • 2021-02-08 15:44

    Passing a Capabilities object to the ChromeDriver() constructor is deprecated. You can find new official doc here.

    ChromeOptions chromeOptions = new ChromeOptions();
    
    Proxy proxy = new Proxy();
    proxy.setAutodetect(false);
    proxy.setHttpProxy("http_proxy-url:port"); 
    proxy.setSslProxy("https_proxy-url:port");
    proxy.setNoProxy("no_proxy-var");
    
    chromeOptions.setCapability("proxy", proxy); 
    driver = new ChromeDriver(chromeOptions);
    
    0 讨论(0)
提交回复
热议问题