如何使用Selenium WebDriver捕获网络流量并查找谷歌分析呼叫



我需要使用自动化测试ga调用

get(LogType.PERFORMANCE).getAll();

提供了一组日志,但找不到呼叫请求url
请帮助查找ga电话。

首先,使用以下代码配置您的网络驱动程序:

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 ); // for new chrome
WebDriver driver = new ChromeDriver(option);

在关闭浏览器之前,使用以下代码捕获文件中的日志:

OutputStream logfile = new FileOutputStream(new File("A text file path where you can save the logs"),true);
PrintStream printlog = new PrintStream(logfile);
LogEntries logs = driver.manage().logs().get(LogType.PERFORMANCE);
for (LogEntry entry : logs) {
if(entry.toString().contains(""type":"XHR"") & entry.toString().contains(""url":"https://example.com/")) {
printlog.append(new Date(entry.getTimestamp()) + " " + entry.toString() +" "+ System.getProperty("line.separator"));
printlog.append(System.getProperty("line.separator"));
printlog.append(System.getProperty("line.separator"));
}
}
printlog.close();

在此代码之后,您可以关闭驱动程序。您将在文件中获得所有通话记录。

要使用PythonSelenium中获取所有性能信息和网络调用,我使用execute_script进行JS调用,该调用将返回性能日志:

# Gets network information, including network calls
def GetNetworkResources(driver):
Resources = driver.execute_script("return window.performance.getEntries();")
for resource in Resources:
print(resource['name'])
return Resources

如果您需要Python以外的解决方案,我可以更新我的答案。

最新更新