Bird
Raised Fist0
Selenium Pythontesting~15 mins

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

Choose your learning style10 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

Practice

(1/5)
1. What is the main advantage of reading test data from a CSV file in Selenium Python tests?
easy
A. It allows running tests with multiple sets of data without changing the code.
B. It makes the test run faster by using CSV format.
C. It automatically fixes bugs in the test code.
D. It encrypts the test data for security.

Solution

  1. Step 1: Understand the purpose of external test data

    Using CSV files lets you separate test data from test code, making tests flexible.
  2. Step 2: Identify the benefit in test execution

    With CSV, you can run the same test multiple times with different inputs easily.
  3. Final Answer:

    It allows running tests with multiple sets of data without changing the code. -> Option A
  4. Quick Check:

    CSV externalizes data = flexible tests [OK]
Hint: CSV stores data separately for easy test reuse [OK]
Common Mistakes:
  • Thinking CSV speeds up test execution
  • Believing CSV fixes code bugs automatically
  • Assuming CSV encrypts data
2. Which Python code snippet correctly opens a CSV file named data.csv for reading test data?
easy
A. file = open('data.csv', 'w')
B. file = open('data.csv', 'r')
C. file = open('data.csv', 'a')
D. file = open('data.csv')

Solution

  1. Step 1: Identify the correct file mode for reading

    To read a file, use mode 'r' which stands for read-only.
  2. Step 2: Check the options

    file = open('data.csv', 'r') uses 'r' mode correctly; others use write ('w'), append ('a'), or default mode which may not be explicit.
  3. Final Answer:

    file = open('data.csv', 'r') -> Option B
  4. Quick Check:

    Read mode = 'r' [OK]
Hint: Use 'r' mode to open files for reading [OK]
Common Mistakes:
  • Using 'w' which overwrites the file
  • Using 'a' which appends instead of reading
  • Not specifying mode explicitly
3. Given the CSV file users.csv with content:
username,password
alice,pass123
bob,secure456

What will the output of this code be?
import csv
with open('users.csv', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)
medium
A. ('username', 'password') ('alice', 'pass123') ('bob', 'secure456')
B. username,password alice,pass123 bob,secure456
C. Error: csv.reader cannot read files
D. ['username', 'password'] ['alice', 'pass123'] ['bob', 'secure456']

Solution

  1. Step 1: Understand csv.reader output

    csv.reader reads each line as a list of strings split by commas.
  2. Step 2: Analyze the print output

    Each row prints as a list, so header and data rows print as lists of strings.
  3. Final Answer:

    ['username', 'password'] ['alice', 'pass123'] ['bob', 'secure456'] -> Option D
  4. Quick Check:

    csv.reader returns lists per row [OK]
Hint: csv.reader returns list of strings per row [OK]
Common Mistakes:
  • Expecting strings instead of lists
  • Confusing tuples with lists
  • Thinking csv.reader raises error on valid files
4. What is wrong with this code snippet that reads CSV data for Selenium tests?
import csv
file = open('testdata.csv')
reader = csv.reader(file)
for row in reader:
    print(row)
file.close()
medium
A. The file is not opened in read mode explicitly.
B. The file is not closed after reading.
C. Using open() without a context manager can cause resource leaks.
D. csv.reader cannot be used with open() function.

Solution

  1. Step 1: Check file handling best practices

    Using open() without 'with' can cause the file to remain open if errors occur.
  2. Step 2: Identify the issue in the code

    Though file.close() is called, if an error happens before, file may not close properly.
  3. Final Answer:

    Using open() without a context manager can cause resource leaks. -> Option C
  4. Quick Check:

    Use 'with' to auto-close files [OK]
Hint: Always use 'with' to open files safely [OK]
Common Mistakes:
  • Thinking file.close() always prevents leaks
  • Believing csv.reader can't work with open()
  • Ignoring explicit read mode is optional
5. You want to run a Selenium test multiple times using usernames and passwords stored in credentials.csv. Which code snippet correctly reads the CSV and uses the data in a test function?
hard
A. import csv with open('credentials.csv', 'r') as file: reader = csv.DictReader(file) for row in reader: username = row['username'] password = row['password'] test_login(username, password)
B. import csv file = open('credentials.csv', 'r') reader = csv.reader(file) for row in reader: test_login(row[0], row[1]) file.close()
C. import csv with open('credentials.csv') as file: reader = csv.reader(file) for row in reader: test_login(row['username'], row['password'])
D. import csv with open('credentials.csv', 'r') as file: reader = csv.reader(file) for row in reader: test_login(row[0], row[1])

Solution

  1. Step 1: Choose correct CSV reading method for named columns

    csv.DictReader reads CSV rows as dictionaries with column names as keys.
  2. Step 2: Use dictionary keys to access username and password

    Accessing row['username'] and row['password'] matches CSV headers and passes correct data.
  3. Final Answer:

    Using csv.DictReader and accessing row['username'] and row['password'] correctly. -> Option A
  4. Quick Check:

    DictReader + keys = clean data access [OK]
Hint: Use csv.DictReader for named column access [OK]
Common Mistakes:
  • Using csv.reader but accessing row by keys
  • Not closing files without 'with' block
  • Forgetting to specify read mode explicitly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard