0
0
Selenium Pythontesting~15 mins

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

Choose your learning style9 modes available
Login test using multiple user credentials from CSV file
Preconditions (2)
Step 1: Open the login page URL.
Step 2: For each row in the CSV file:
Step 3: Enter the 'username' value into the username input field with id 'username'.
Step 4: Enter the 'password' value into 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' indicating successful login.
Step 7: Log out by clicking the logout button with id 'logoutBtn' to prepare for next iteration.
✅ Expected Result: For each set of credentials in the CSV, the user successfully logs in and is redirected to the dashboard page.
Automation Requirements - Selenium with Python unittest
Assertions Needed:
Verify current URL is 'https://example.com/dashboard' after login
Verify login fields accept input
Verify logout button is clickable after login
Best Practices:
Use explicit waits to wait for elements to be visible or clickable
Use Python's csv module to read test data
Use setUp and tearDown methods for browser setup and cleanup
Use try-except blocks to handle exceptions gracefully
Close browser after all tests
Automated Solution
Selenium Python
import unittest
import csv
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

class TestLoginWithCSV(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.maximize_window()
        self.wait = WebDriverWait(self.driver, 10)

    def test_login_from_csv(self):
        driver = self.driver
        wait = self.wait
        driver.get('https://example.com/login')

        with open('login_data.csv', newline='') as csvfile:
            reader = csv.DictReader(csvfile)
            for row in reader:
                username = row['username']
                password = row['password']

                # Enter username
                username_field = wait.until(EC.visibility_of_element_located((By.ID, 'username')))
                username_field.clear()
                username_field.send_keys(username)

                # Enter password
                password_field = wait.until(EC.visibility_of_element_located((By.ID, 'password')))
                password_field.clear()
                password_field.send_keys(password)

                # Click login button
                login_button = wait.until(EC.element_to_be_clickable((By.ID, 'loginBtn')))
                login_button.click()

                # Verify URL changed to dashboard
                wait.until(EC.url_to_be('https://example.com/dashboard'))
                self.assertEqual(driver.current_url, 'https://example.com/dashboard')

                # Verify logout button is clickable
                logout_button = wait.until(EC.element_to_be_clickable((By.ID, 'logoutBtn')))
                self.assertTrue(logout_button.is_displayed())

                # Click logout to prepare for next test
                logout_button.click()

                # Wait for login page to load again
                wait.until(EC.visibility_of_element_located((By.ID, 'username')))

    def tearDown(self):
        self.driver.quit()

if __name__ == '__main__':
    unittest.main()

This test script uses Python's unittest framework and Selenium WebDriver.

In setUp, we open the browser and prepare a wait object for explicit waits.

The test test_login_from_csv reads the CSV file using Python's csv.DictReader to get username and password pairs.

For each row, it:

  • Waits for username and password fields to be visible, clears them, and enters the data.
  • Waits for the login button to be clickable and clicks it.
  • Waits until the URL changes to the dashboard URL and asserts it is correct.
  • Waits for the logout button to be clickable and asserts it is displayed.
  • Clicks logout to return to the login page for the next iteration.

Finally, tearDown closes the browser after all tests.

This approach uses explicit waits to avoid timing issues and reads test data cleanly from CSV, making the test easy to maintain and extend.

Common Mistakes - 5 Pitfalls
{'mistake': 'Using time.sleep() instead of explicit waits', 'why_bad': 'It makes tests slower and flaky because fixed waits may be too short or too long.', 'correct_approach': "Use Selenium's explicit waits like WebDriverWait with expected_conditions."}
Hardcoding test data inside the test script
Not clearing input fields before sending keys
Not closing the browser after tests
Using brittle locators like absolute XPaths
Bonus Challenge

Now add data-driven testing with 3 different CSV files for different environments (e.g., dev, staging, production).

Show Hint