Bird
Raised Fist0
Selenium Pythontesting~15 mins

Base page class in Selenium Python - Build an Automation Script

Choose your learning style10 modes available
Create and use a Base Page class for Selenium tests
Preconditions (3)
Step 1: Create a BasePage class that accepts a WebDriver instance in its constructor
Step 2: Add a method 'open_url' that navigates the browser to a given URL
Step 3: Add a method 'find_element' that takes a locator tuple and returns the web element
Step 4: Add a method 'click' that clicks on an element found by a locator
Step 5: Add a method 'enter_text' that sends text to an element found by a locator
Step 6: Create a test script that uses the BasePage class to open the sample page
Step 7: Use the BasePage methods to find an input field, enter text, and click a button
Step 8: Verify that the expected page or element is displayed after the actions
✅ Expected Result: The test script runs without errors, opens the page, interacts with elements using BasePage methods, and verifies the expected outcome successfully.
Automation Requirements - selenium with unittest
Assertions Needed:
Verify the page URL after navigation
Verify that an element is present after interaction
Best Practices:
Use explicit waits to wait for elements
Use By locators for element identification
Keep BasePage methods generic and reusable
Use unittest framework for test structure
Automated Solution
Selenium Python
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.

Common Mistakes - 4 Pitfalls
Using time.sleep() instead of explicit waits
Hardcoding locators inside test methods instead of BasePage
Not clearing input fields before sending keys
Not quitting the driver after tests
Bonus Challenge

Now add data-driven testing with 3 different username and password combinations.

Show Hint

Practice

(1/5)
1. What is the main purpose of a BasePage class in Selenium Python testing?
easy
A. To group common web page actions and locators for reuse
B. To store test data for different test cases
C. To define the browser settings and capabilities
D. To generate test reports automatically

Solution

  1. Step 1: Understand the role of BasePage

    The BasePage class is designed to hold common actions and locators shared by multiple page classes.
  2. Step 2: Compare with other options

    Storing test data, browser settings, or generating reports are not responsibilities of BasePage.
  3. Final Answer:

    To group common web page actions and locators for reuse -> Option A
  4. Quick Check:

    BasePage groups common actions [OK]
Hint: BasePage holds shared page methods and locators [OK]
Common Mistakes:
  • Confusing BasePage with test data storage
  • Thinking BasePage manages browser setup
  • Assuming BasePage creates reports
2. Which of the following is the correct way to define a locator tuple in a BasePage class?
easy
A. submit_button = (By.ID, 'submit')
B. submit_button = ['id', 'submit']
C. submit_button = {'id': 'submit'}
D. submit_button = By.ID('submit')

Solution

  1. Step 1: Recall locator tuple syntax

    Locator tuples use the format (By.<METHOD>, 'value'), e.g., (By.ID, 'submit').
  2. Step 2: Check each option

    submit_button = (By.ID, 'submit') matches the tuple format. The other options use wrong data structures or invalid syntax.
  3. Final Answer:

    submit_button = (By.ID, 'submit') -> Option A
  4. Quick Check:

    Locator tuple = (By.METHOD, 'value') [OK]
Hint: Locator tuples always use parentheses and By constants [OK]
Common Mistakes:
  • Using lists or dicts instead of tuples for locators
  • Calling By.ID as a function
  • Missing parentheses around locator tuple
3. Given this BasePage method, what will page.get_title() return if the browser's current page title is "Welcome Page"?
class BasePage:
    def __init__(self, driver):
        self.driver = driver

    def get_title(self):
        return self.driver.title

page = BasePage(driver)
medium
A. An error because get_title has no return
B. self.driver
C. None
D. "Welcome Page"

Solution

  1. Step 1: Understand get_title method

    The method returns self.driver.title, which is the current page title string.
  2. Step 2: Check given title

    The browser's current page title is "Welcome Page", so the method returns that string.
  3. Final Answer:

    "Welcome Page" -> Option D
  4. Quick Check:

    get_title returns driver.title = "Welcome Page" [OK]
Hint: get_title returns driver.title string [OK]
Common Mistakes:
  • Thinking it returns the driver object
  • Assuming no return means None
  • Confusing method with attribute
4. Identify the error in this BasePage method and how to fix it:
class BasePage:
    def __init__(self, driver):
        self.driver = driver

    def click_element(locator):
        element = self.driver.find_element(*locator)
        element.click()
medium
A. Using find_element instead of find_elements
B. Missing 'self' parameter in click_element method
C. Locator should be a string, not a tuple
D. element.click() should be element.click

Solution

  1. Step 1: Check method parameters

    Instance methods must have 'self' as the first parameter. Here, click_element lacks 'self'.
  2. Step 2: Understand impact

    Without 'self', calling click_element will cause a TypeError because 'self.driver' is undefined.
  3. Final Answer:

    Missing 'self' parameter in click_element method -> Option B
  4. Quick Check:

    Instance methods need 'self' first [OK]
Hint: Always include 'self' as first method parameter [OK]
Common Mistakes:
  • Forgetting 'self' in instance methods
  • Confusing find_element with find_elements
  • Misunderstanding locator types
  • Using method call without parentheses
5. You want to create a BasePage method is_element_visible that returns True if an element is visible and False if not, without raising exceptions. Which is the best way to implement it?
hard
A. Use driver.page_source to search for element HTML string
B. Call find_element and return True without exception handling
C. Use try-except to catch NoSuchElementException and return False if caught
D. Use find_elements and check if list length is greater than zero

Solution

  1. Step 1: Understand element visibility check

    Using find_element raises NoSuchElementException if element not found, so we must handle it.
  2. Step 2: Use try-except for safe check

    Try to find element and check is_displayed(). If exception occurs, return False safely.
  3. Final Answer:

    Use try-except to catch NoSuchElementException and return False if caught -> Option C
  4. Quick Check:

    Try-except handles missing element safely [OK]
Hint: Wrap find_element in try-except to avoid exceptions [OK]
Common Mistakes:
  • Not handling exceptions causing test failure
  • Assuming find_elements always returns visible elements
  • Searching page_source is unreliable and slow
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