0
0
Selenium Pythontesting~5 mins

Performance metrics collection in Selenium Python

Choose your learning style9 modes available
Introduction
Collecting performance metrics helps you understand how fast and smooth a website works. It shows if pages load quickly or if something slows them down.
Checking how fast a website loads after changes.
Finding slow parts of a page to improve user experience.
Comparing performance before and after adding new features.
Monitoring website speed regularly to catch problems early.
Syntax
Selenium Python
performance = driver.execute_script('return window.performance.timing')
This code runs JavaScript inside the browser to get timing data.
The 'performance' object contains many useful time points about page loading.
Examples
Calculate total page load time by subtracting navigation start from load event end.
Selenium Python
performance = driver.execute_script('return window.performance.timing')
print(performance['loadEventEnd'] - performance['navigationStart'])
Get all resource load times like images and scripts.
Selenium Python
performance = driver.execute_script('return window.performance.getEntriesByType("resource")')
for resource in performance:
    print(resource['name'], resource['duration'])
Sample Program
This script opens a website in headless Chrome, collects page load timing, calculates total load time, and prints it.
Selenium Python
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument('--headless')
service = Service()
driver = webdriver.Chrome(service=service, options=options)

driver.get('https://example.com')
performance = driver.execute_script('return window.performance.timing')

load_time = performance['loadEventEnd'] - performance['navigationStart']
print(f'Page load time: {load_time} ms')

driver.quit()
OutputSuccess
Important Notes
Sometimes 'loadEventEnd' can be 0 if the page is not fully loaded yet; wait or check before calculating.
Performance timing data is in milliseconds since navigation started.
Headless mode runs browser without opening a window, useful for automated tests.
Summary
Performance metrics show how fast a page loads and resources load.
Use JavaScript execution in Selenium to get performance data.
Calculate load times by subtracting key timestamps from the performance object.