Network log capture in Selenium Python - Build an Automation Script
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By import json # Setup Chrome options to enable performance logging chrome_options = Options() chrome_options.add_experimental_option('w3c', False) # Disable W3C to access performance logs chrome_options.set_capability('goog:loggingPrefs', {'performance': 'ALL'}) # Initialize WebDriver service = Service() driver = webdriver.Chrome(service=service, options=chrome_options) try: driver.get('https://example.com') # Wait until the page's main element is loaded (example: <h1> tag) WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.TAG_NAME, 'h1')) ) # Get performance logs logs = driver.get_log('performance') # Parse logs to find network requests network_requests = [] for entry in logs: message = json.loads(entry['message'])['message'] if message['method'] == 'Network.requestWillBeSent': url = message['params']['request']['url'] network_requests.append(url) # Assertions assert len(network_requests) > 0, 'No network requests found in logs' assert any('https://example.com' in url for url in network_requests), 'No request to https://example.com found' finally: driver.quit()
This script starts by setting Chrome options to enable performance logging, which is necessary to capture network logs.
We disable W3C mode because ChromeDriver currently requires this to access performance logs.
After launching the browser, it navigates to 'https://example.com' and waits explicitly for an <h1> element to appear, indicating the page loaded.
Then it retrieves the performance logs and parses each log entry to find network requests by checking for the 'Network.requestWillBeSent' event.
It collects all request URLs and asserts that there is at least one network request and that one of them contains 'https://example.com'.
Finally, it closes the browser to clean up.
Now add data-driven testing with 3 different URLs: 'https://example.com', 'https://www.wikipedia.org', and 'https://www.python.org'. For each URL, capture network logs and verify requests.