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

vatpfxk5  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(659)

我想捕获chromedriver窗口中生成的网络流量。我发现可以使用Selenium4.0devtools实用工具来完成,但是我可以´找不到一个好的文档或如何使用。
https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/devtools/devtools.html
有最简单的方法吗?谢谢

y3bcpkx1

y3bcpkx11#

你可以使用 LoggingPreferences 以及 ChromeOptions 进口

  1. import org.json.simple.JSONObject;
  2. import org.json.simple.parser.JSONParser;
  3. import org.json.simple.parser.ParseException;
  4. import org.openqa.selenium.WebDriver;
  5. import org.openqa.selenium.chrome.ChromeDriver;
  6. import org.openqa.selenium.chrome.ChromeOptions;
  7. import org.openqa.selenium.logging.LogEntries;
  8. import org.openqa.selenium.logging.LogEntry;
  9. import org.openqa.selenium.logging.LogType;
  10. import org.openqa.selenium.logging.LoggingPreferences;
  11. import org.openqa.selenium.remote.CapabilityType;

这里我们得到json字符串,其中包含关于in-log记录的数据。我用 json-simple 库将接收到的json字符串转换为jsonobject。

  1. LoggingPreferences preferences = new LoggingPreferences();
  2. preferences.enable(LogType.PERFORMANCE, Level.ALL);
  3. ChromeOptions option = new ChromeOptions();
  4. option.setCapability(CapabilityType.LOGGING_PREFS, preferences);
  5. option.setCapability("goog:loggingPrefs", preferences);
  6. option.addArguments();
  7. System.setProperty("webdriver.chrome.driver", "chrome_driver_path");
  8. ChromeDriver chromeDriver = new ChromeDriver(option);
  9. chromeDriver.manage().window().maximize();
  10. this.driver = chromeDriver;
  11. driver.get("website_url");
  12. LogEntries logs = driver.manage().logs().get(LogType.PERFORMANCE);
  13. for (LogEntry entry : logs) {
  14. JSONParser parser = new JSONParser();
  15. JSONObject jsonObject = null;
  16. try {
  17. jsonObject = (JSONObject) parser.parse(entry.getMessage());
  18. } catch (ParseException e) {
  19. e.printStackTrace();
  20. }
  21. JSONObject messageObject = (JSONObject) jsonObject.get("message");
  22. System.out.println(messageObject.toJSONString());
  23. // You can do the required processing to messageObject
  24. }

您可以使用从日志中筛选网络呼叫的类型 type json字符串中的(xhr、脚本、样式表)。

  1. for (LogEntry entry : logs) {
  2. if(entry.toString().contains("\"type\":\"XHR\"")) {
  3. }
  4. }
展开查看全部

相关问题