What is network traffic?
It includes all the network requests the browser makes when retrieving and loading the Javascript, CSS, image files, and more for a single web page. In lay terms, it is the communication between the browser and server when it is loading a web page.
Collecting Network Events using Selenium WebDriver is simple, you just need to enable performance logging in Chrome Desired capabilities. Once you enable Performance Log, Timeline, Network, and Page events can be collected.
Enabling Logging in Desired Capabilities
DesiredCapabilities caps = DesiredCapabilities.chrome();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.INFO);
caps.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
Collecting Network Events
WebDriver driver=new RemoteWebDriver(new URL(“https://localhost:4444/wd/hub”), caps);
driver.get(“https://siligentlogic.com/vlogs/”);
List<LogEntry> entries = driver.manage().logs().get(LogType.PERFORMANCE).getAll();
System.out.println(entries.size() + ” ” + LogType.PERFORMANCE + ” log entries found”);
for (LogEntry entry : entries) {
System.out.println(new Date(entry.getTimestamp()) + ” ” + entry.getLevel() + ” ” + entry.getMessage());
}
A shortcode for reference can be like:
mport org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
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;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class ChromeConsoleLogging {
private WebDriver driver;
@BeforeMethod
public void setUp() {
System.setProperty(“webdriver.chrome.driver”, “c:\\path\\to\\chromedriver.exe”);
DesiredCapabilities caps = DesiredCapabilities.chrome();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.BROWSER, Level.ALL);
caps.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
driver = new ChromeDriver(caps);
}
@AfterMethod
public void tearDown() {
driver.quit();
}
public void analyzeLog() {
LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);
for (LogEntry entry : logEntries) {
System.out.println(new Date(entry.getTimestamp()) + ” ” + entry.getLevel() + ” ” + entry.getMessage());
//do something useful with the data
}
}
@Test
public void testMethod() {
driver.get(“http://mypage.com”);
//do something on page
analyzeLog();
}
}