0
0
Selenium Pythontesting~5 mins

Reading test data from JSON in Selenium Python

Choose your learning style9 modes available
Introduction

We use JSON files to keep test data separate from test code. This helps us change data easily without touching the test steps.

When you want to test a website with different user names and passwords.
When you need to run the same test with many sets of data.
When you want to keep your test data organized and easy to update.
When sharing test data with other team members or tools.
When you want to avoid hardcoding values inside your test scripts.
Syntax
Selenium Python
import json

with open('data.json') as file:
    data = json.load(file)

# Access data like this:
username = data['username']
password = data['password']

Use json.load() to read JSON data from a file.

Make sure the JSON file is in the correct folder or provide the full path.

Examples
This reads a JSON file named user_data.json and prints the email value.
Selenium Python
import json

with open('user_data.json') as f:
    user = json.load(f)

print(user['email'])
This example loads a config file and prints the URL to test.
Selenium Python
import json

with open('config.json') as f:
    config = json.load(f)

url = config['url']
print(f"Testing URL: {url}")
Sample Program

This script reads login data from testdata.json, opens a browser, enters the data, clicks login, and checks if login succeeded.

Selenium Python
import json
from selenium import webdriver
from selenium.webdriver.common.by import By

# Load test data from JSON file
def load_test_data(filename):
    with open(filename) as file:
        return json.load(file)

# Test function using Selenium and JSON data
def test_login():
    data = load_test_data('testdata.json')
    driver = webdriver.Chrome()
    driver.get(data['url'])

    # Find username and password fields and enter data
    driver.find_element(By.ID, 'username').send_keys(data['username'])
    driver.find_element(By.ID, 'password').send_keys(data['password'])

    # Click login button
    driver.find_element(By.ID, 'loginBtn').click()

    # Check if login was successful by looking for logout button
    logout_button = driver.find_element(By.ID, 'logoutBtn')
    assert logout_button.is_displayed(), 'Login failed!'

    driver.quit()

# Run the test
if __name__ == '__main__':
    test_login()
OutputSuccess
Important Notes

Always close the browser after the test to free resources.

Keep your JSON file simple and well-structured for easy reading.

Use meaningful keys in JSON to avoid confusion.

Summary

Reading test data from JSON helps separate data from code.

Use Python's json module to load data easily.

This makes tests easier to maintain and reuse with different data.