0
0
Selenium Pythontesting~15 mins

Reading test data from JSON in Selenium Python - Build an Automation Script

Choose your learning style9 modes available
Login test using credentials from JSON file
Preconditions (2)
Step 1: Open the login page URL
Step 2: Read the username and password from 'testdata.json'
Step 3: Enter the username in the email input field with id 'email'
Step 4: Enter the password in the password input field with id 'password'
Step 5: Click the login button with id 'loginBtn'
Step 6: Verify that the URL changes to 'https://example.com/dashboard' after login
✅ Expected Result: User is successfully logged in and redirected to the dashboard page
Automation Requirements - Selenium with Python
Assertions Needed:
Verify the current URL is 'https://example.com/dashboard' after login
Best Practices:
Use explicit waits to wait for elements to be interactable
Use By locators with id for element selection
Read test data from external JSON file
Use try-except blocks to handle exceptions gracefully
Automated Solution
Selenium Python
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.

Common Mistakes - 4 Pitfalls
Hardcoding test data inside the test script instead of reading from JSON
Using time.sleep() instead of explicit waits
Using incorrect or brittle locators like absolute XPath
Not closing the browser after test execution
Bonus Challenge

Now add data-driven testing with 3 different sets of login credentials read from the JSON file

Show Hint