Get All network requests Using selenium 4.6.0
A.N.M Zakaria Shahed
ISTQB Certified CTFL & Agile tester | Test Automation | Team Lead | Ex BJIT
When we write automation scripts there have lots of places where we need validation from the network tab, we need a response, and request value and sometimes we need to intercept the network request. Before selenium 4 it was impossible to get network requests. But in selenium 4 there has an opportunity to capture all the network requests.
Add a new version of Selenium
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java --
<dependency>
??<groupId>org.seleniumhq.selenium</groupId>
??<artifactId>selenium-java</artifactId>
??<version>4.6.0</version>
</dependency>>
Create session with devtools
DevTools devTools = driver.getDevTools();
devTools.createSession();
Set Max total buffer size , Max resource buffer size , Max post data size.
I set here emptry by Optional.empty functtion.
devTools.send(Network.enable(Optional.empty(),Optional.empty(),Optional.empty()));
Now add listener to capture all the network
devTools.addListener
Inside the request you will get your all network call and you can do any operation there, I just simply print the request
Here is full code
public static void main(String[] args) throws InterruptedException, AWTException {
ChromeOptions options = new ChromeOptions();
ChromeDriver driver = new ChromeDriver(options);
driver.get("https://www.google.com");
DevTools devTools = driver.getDevTools();
devTools.createSession();
devTools.send(Network.enable(Optional.empty(),Optional.empty(),Optional.empty()));
devTools.addListener(Network.requestWillBeSent(),
request ->{
System.out.println("Request URL:"+request.getRequest().getUrl());
System.out.println("Request Method:"+request.getRequest().getMethod());
System.out.println("Request Method:"+request.getRequest().getHeaders().toJson());
});
Thread.sleep(50000);
}
Thanks
A.N.M ZAKARIA SHAHED
Test automation engineer