0
0
Selenium Pythontesting~15 mins

Element locators in page class in Selenium Python - Build an Automation Script

Choose your learning style9 modes available
Verify login button is visible on the login page
Preconditions (2)
Step 1: Open the browser and navigate to 'https://example.com/login'
Step 2: Locate the login button using the page class locator
Step 3: Check if the login button is visible on the page
✅ Expected Result: The login button is visible on the login page
Automation Requirements - Selenium with Python
Assertions Needed:
Assert that the login button element is displayed
Best Practices:
Use a Page Object Model (POM) class to store element locators
Use explicit waits to wait for elements to be visible
Use By.ID or By.CSS_SELECTOR for locators instead of brittle XPath
Keep test code clean by separating page locators and test logic
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

class LoginPage:
    # Element locators stored as class variables
    LOGIN_BUTTON = (By.ID, 'login-button')

    def __init__(self, driver):
        self.driver = driver

    def is_login_button_visible(self):
        wait = WebDriverWait(self.driver, 10)
        login_button = wait.until(EC.visibility_of_element_located(self.LOGIN_BUTTON))
        return login_button.is_displayed()


def test_login_button_visibility():
    driver = webdriver.Chrome()
    driver.get('https://example.com/login')

    login_page = LoginPage(driver)
    assert login_page.is_login_button_visible(), 'Login button should be visible on login page'

    driver.quit()

The LoginPage class stores the login button locator as a class variable LOGIN_BUTTON using By.ID. This keeps locators organized and easy to maintain.

The method is_login_button_visible uses an explicit wait to wait up to 10 seconds for the login button to be visible. This avoids timing issues.

The test function test_login_button_visibility opens the browser, navigates to the login page, creates a LoginPage object, and asserts the login button is visible. Finally, it closes the browser.

This structure follows best practices by separating locators in a page class and using explicit waits and clear assertions.

Common Mistakes - 3 Pitfalls
Hardcoding XPath locators that are brittle
Not using explicit waits before checking element visibility
Mixing locators directly in test code instead of page class
Bonus Challenge

Now add data-driven testing with 3 different login page URLs to verify the login button visibility on each

Show Hint