Base page class in Selenium Python - Build an Automation Script
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 import unittest class BasePage: def __init__(self, driver): self.driver = driver self.wait = WebDriverWait(driver, 10) def open_url(self, url: str): self.driver.get(url) def find_element(self, locator: tuple): return self.wait.until(EC.presence_of_element_located(locator)) def click(self, locator: tuple): element = self.find_element(locator) element.click() def enter_text(self, locator: tuple, text: str): element = self.find_element(locator) element.clear() element.send_keys(text) class TestSamplePage(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() self.base_page = BasePage(self.driver) def test_open_and_interact(self): url = "https://example.com/login" self.base_page.open_url(url) self.assertEqual(self.driver.current_url, url) username_locator = (By.ID, "username") password_locator = (By.ID, "password") login_button_locator = (By.ID, "loginBtn") self.base_page.enter_text(username_locator, "testuser") self.base_page.enter_text(password_locator, "password123") self.base_page.click(login_button_locator) dashboard_locator = (By.ID, "dashboard") dashboard_element = self.base_page.find_element(dashboard_locator) self.assertTrue(dashboard_element.is_displayed()) def tearDown(self): self.driver.quit() if __name__ == '__main__': unittest.main()
The BasePage class is designed to hold common browser actions. It takes a driver and creates a WebDriverWait for explicit waits.
The open_url method navigates to a URL.
The find_element method waits until the element is present and returns it.
The click and enter_text methods use find_element to interact with elements safely.
The TestSamplePage class uses Python's unittest framework. It sets up the Chrome driver and BasePage instance.
The test opens a login page URL, verifies the URL, enters username and password, clicks login, then verifies the dashboard is displayed.
Finally, tearDown quits the browser to clean up.
This structure keeps code clean, reusable, and easy to maintain.
Now add data-driven testing with 3 different username and password combinations.