简体   繁体   English

使用 selenium webdriver java 4.0v 捕获网络流量

[英]Capture network traffic using selenium webdriver java 4.0v

I would like to capture the network traffic generated in a Chromedriver window.我想捕获在 Chromedriver 窗口中生成的网络流量。 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.我发现它可以使用 selenium 4.0 DevTools 实用程序来完成,但我找不到方法或好的文档。

https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/devtools/DevTools.html 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您可以使用LoggingPreferencesChromeOptions完成此操作

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.在这里,我们得到 Json 字符串,其中包含有关日志记录的数据。 I use json-simple library to convert the received json String to JSONObject.我使用json-simple库将接收到的 json 字符串转换为 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.您可以使用 json 字符串中的type (XHR、脚本、样式表)从日志中过滤网络调用的type

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 )这是一个使用 Selenium 4 提供的新 DevTools 协议 (CDP) 的简单示例(此代码使用 Beta-4 版本和适用于 Chrome 91 的 CDP)

            :
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.使用 Selenium 4,您可以获得请求 URL 和响应 URL 等。

<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.享受。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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