How can I capture network traffic of a specific page using Selenium?

SeleniumAutomation TestingTesting Tools

We can capture network traffic on a specific page using Selenium webdriver in Python. To achieve this, we take the help of the JavaScript Executor. Selenium can execute JavaScript commands with the help of the execute_script method.

JavaScript command to be executed is passed as a parameter to this method. To capture the network traffic, we have to pass the command: return window.performance.getEntries() as a parameter to the execute_script method.

Syntax

r = driver.execute_script("return window.performance.getEntries();")

Example

Code Implementation

from selenium import webdriver
#configure chromedriver path
driver = webdriver.Chrome(executable_path='../drivers/chromedriver')
#implicit wait
driver.implicitly_wait(0.5)
#url launch
driver.get("https://www.google.com/")
#JavaScript command to traffic
r = driver.execute_script("return window.performance.getEntries();")
for res in r:
print(res['name'])
#browser close
driver.close()

Output

raja
Published on 29-Jun-2021 08:22:52
Advertisements