Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I capture network traffic and find google analytics call using Selenium WebDriver?

I need to test for ga call using automation.

get(LogType.PERFORMANCE).getAll();

gives set of logs, but couldn't find the call request url.
Please help in finding the ga call.

like image 966
Arun Prasanth.G Avatar asked Mar 05 '23 20:03

Arun Prasanth.G


2 Answers

First, configure your webdriver with below code:

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);

Before closing the browser, use below code to capture the logs in file:

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();

After this code you can close the driver. You will get all the call logs in the file.

like image 117
Ankit Gupta Avatar answered Mar 10 '23 10:03

Ankit Gupta


To get all performance information and network calls in Selenium using Python, I use execute_script to make a JS call that will return the performance logs:

# 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

If you need a solution other than Python I can update my answer.

like image 41
PixelEinstein Avatar answered Mar 10 '23 10:03

PixelEinstein