简体   繁体   中英

Capture network traffic using selenium webdriver java 4.0v

I would like to capture the network traffic generated in a Chromedriver window. I have found out that it can be done using selenium 4.0 DevTools utility but I can´t find how to or a good documentation.

https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/devtools/DevTools.html

Is there an easiest way to do? Thanks

在此处输入图片说明

You can get this done using LoggingPreferences and ChromeOptions

imports

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.remote.CapabilityType;

Here We get Json String which contain data about the in log records. I use json-simple library to convert the received json String to JSONObject.

LoggingPreferences preferences = new LoggingPreferences();
preferences.enable(LogType.PERFORMANCE, Level.ALL);

ChromeOptions option = new ChromeOptions();
option.setCapability(CapabilityType.LOGGING_PREFS, preferences);
option.setCapability("goog:loggingPrefs", preferences);
option.addArguments();

System.setProperty("webdriver.chrome.driver", "chrome_driver_path");

ChromeDriver chromeDriver = new ChromeDriver(option);
chromeDriver.manage().window().maximize();
this.driver = chromeDriver;


driver.get("website_url");

LogEntries logs = driver.manage().logs().get(LogType.PERFORMANCE);
for (LogEntry entry : logs) {
    JSONParser parser = new JSONParser();
    JSONObject jsonObject = null;
    try {
        jsonObject = (JSONObject) parser.parse(entry.getMessage());
    } catch (ParseException e) {
        e.printStackTrace();
    }
    JSONObject messageObject = (JSONObject) jsonObject.get("message");
    System.out.println(messageObject.toJSONString());
    // You can do the required processing to messageObject
}

You can filter the type of network calls from logs using type (XHR, Script, Stylesheet) in the json String.

for (LogEntry entry : logs) {
   if(entry.toString().contains("\"type\":\"XHR\"")) {
   }
}

Here's a simple example using the new DevTools protocol (CDP) available from Selenium 4 (this code uses the Beta-4 version and CDP for Chrome 91 )

            :
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.v91.network.*;
            :
            
    DevTools devTools = ((ChromiumDriver) driver).getDevTools();
    devTools.createSession();
    devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));
    
    devTools.addListener(Network.requestWillBeSent(), entry -> {
                System.out.println("Request (id) URL      : (" + entry.getRequestId() + ") " 
                        + entry.getRequest().getUrl()
                        + " (" + entry.getRequest().getMethod() + ")");
            });
    
    devTools.addListener(Network.responseReceived(), entry -> {
                System.out.println("Response (Req id) URL : (" + entry.getRequestId() + ") " 
                        + entry.getResponse().getUrl()
                        + " (" + entry.getResponse().getStatus() + ")");
            }); 
    
    driver.get("someurl");  // on so on ... 

    

Using Selenium 4 you can get requests URL and Response URLs and more.

<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>4.0.0</version>
</dependency>

<dependency>
    <groupId>io.github.bonigarcia</groupId>
    <artifactId>webdrivermanager</artifactId>
    <version>4.3.1</version>
</dependency>

Using this snippet you will get all requests and responses.


    @BeforeEach
    public void setUp() {
        WebDriverManager.chromedriver().setup();
        this.chromeDriver = new ChromeDriver();
        devTools = chromeDriver.getDevTools();
        devTools.createSession();
    }

    @Test
    public void getRequestsAndResponseUrls() throws InterruptedException {
        devTools.send(new Command<>("Network.enable", ImmutableMap.of()));
;
        devTools.addListener(Network.responseReceived(), l -> {
            System.out.print("Response URL: ");
            System.out.println(l.getResponse().getUrl());
        });
        devTools.addListener(Network.requestWillBeSent(), l -> {
            System.out.print("Request URL: ");
            System.out.println(l.getRequest().getUrl());
        });

        chromeDriver.get("https://edition.cnn.com/");

        // While Thread.sleep you you will see requests and responses appearing in console. 
        Thread.sleep(10000);
    }

Enjoy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM