Reading test data from JSON in Selenium Python - Build an Automation Script
import json from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException # Load test data from JSON file def load_test_data(filepath): with open(filepath, 'r', encoding='utf-8') as file: return json.load(file) def test_login_with_json_data(): data = load_test_data('testdata.json') username = data['username'] password = data['password'] driver = webdriver.Chrome() wait = WebDriverWait(driver, 10) try: driver.get('https://example.com/login') # Wait for email input and enter username email_input = wait.until(EC.element_to_be_clickable((By.ID, 'email'))) email_input.clear() email_input.send_keys(username) # Wait for password input and enter password password_input = wait.until(EC.element_to_be_clickable((By.ID, 'password'))) password_input.clear() password_input.send_keys(password) # Wait for login button and click login_button = wait.until(EC.element_to_be_clickable((By.ID, 'loginBtn'))) login_button.click() # Wait for URL to change to dashboard wait.until(EC.url_to_be('https://example.com/dashboard')) assert driver.current_url == 'https://example.com/dashboard', f"Expected URL to be dashboard but got {driver.current_url}" except TimeoutException as e: assert False, f"Timeout waiting for element or URL change: {e}" finally: driver.quit() if __name__ == '__main__': test_login_with_json_data()
This script starts by loading the username and password from an external JSON file named testdata.json. This keeps test data separate from code, which is a good practice.
We use Selenium WebDriver to open the login page. Explicit waits ensure the script waits until the email and password fields and the login button are clickable before interacting with them. This avoids errors from trying to use elements too early.
After entering the credentials and clicking login, the script waits until the URL changes to the dashboard URL. Then it asserts that the current URL is exactly the dashboard URL, confirming successful login.
Try-except blocks catch timeout exceptions to fail the test gracefully if elements do not appear in time.
Finally, the browser is closed in the finally block to clean up regardless of test outcome.
Now add data-driven testing with 3 different sets of login credentials read from the JSON file