What is Proxy?
A proxy server acts as an intermediary for requests between a client and a server. In simple terms, the traffic flows through the proxy server on its way to the address you requested and back.
A proxy server for automation scripts with Selenium could be helpful for:
- Capture network traffic
- Mock backend calls made by the website
- Access the required website under complex network topologies or strict corporate restrictions/policies.
1. Create an instance of FirefoxOptions
FirefoxOptions options = new FirefoxOptions();
2. Set the desired preferences or proxy configuration
Create an instance of ChromeOptions and set the proxy:
options.addPreference("network.proxy.type", 1);
options.addPreference("network.proxy.http", proxyAddress);
options.addPreference("network.proxy.http_port", proxyPort);
Replace “proxyAddress” with your actual proxy address and “proxyPort“ with the appropriate port number.
network.proxy.type is a preference that determines the type of proxy being used. It is a configuration option that can be set to different values to specify the proxy type.
The possible values for network.proxy.type are:
– 0: Direct connection (no proxy)
– 1: Manual proxy configuration
– 2: Proxy auto-configuration (PAC)
– 4: Auto-detect proxy settings
Launch Firefox WebDriver with the configured options:
driver = new FirefoxDriver(options);
The complete program is mentioned below:
package org.example;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
public class FireFoxProxyDemo {
public static void main(String[] args) {
// Set the proxy server details
String proxyAddress = "localhost";
int proxyPort = 8080;
FirefoxDriver driver;
// Create an instance of `FirefoxOptions` and set the proxy configuration
FirefoxOptions options = new FirefoxOptions();
options.addPreference("network.proxy.type", 1);
options.addPreference("network.proxy.http", proxyAddress);
options.addPreference("network.proxy.http_port", proxyPort);
// Instantiate FireFox Driver with the configured options
driver = new FirefoxDriver(options);
// Perform your browsing actions using the driver
driver.get("https://www.google.com");
System.out.println("Page Title :" + driver.getTitle());
// Close the browser session
driver.quit();
}
}
The output of the above program is
![](https://qaautomation.expert/wp-content/uploads/2024/05/image-16.png?w=705)
That’s it! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!