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. Setting up Proxy using Selenium
Create an instance of Proxy and set the proxy configuration:
// Set the proxy server details
String proxyAddress = "proxy.example";
int proxyPort = 8080;
// Create a Proxy object and set the HTTP proxy details
Proxy proxy = new Proxy();
proxy.setHttpProxy(proxyAddress + ":" + proxyPort);
Replace “your_proxy_address” with the actual proxy address and “port” with the appropriate port number.
setHttpProxy – Specify which proxy to use for HTTP connections
2. Configure Chrome options with the Proxy object
Create an instance of ChromeOptions and set the proxy:
ChromeOptions options = new ChromeOptions();
options.setProxy(proxy);
Launch Chrome WebDriver with the configured options:
WebDriver driver = new ChromeDriver(options);
The complete program is mentioned below:
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class ProxyDemo {
public static void main(String[] args) {
// Set the proxy server details
String proxyAddress = "localhost";
int proxyPort = 8080;
// Create a Proxy object and set the HTTP proxy details
Proxy proxy = new Proxy();
proxy.setHttpProxy(proxyAddress + ":" + proxyPort);
// Configure Chrome options with the Proxy object
ChromeOptions options = new ChromeOptions();
options.setProxy(proxy);
options.addArguments("start-maximized");
// Instantiate ChromeDriver with the configured options
WebDriver driver = new ChromeDriver(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-15.png?w=792)