Bird
Raised Fist0
Selenium Pythontesting~5 mins

Element locators in page class in Selenium Python

Choose your learning style10 modes available
Introduction

We use element locators in a page class to find parts of a web page easily and clearly. This helps us write tests that are simple and organized.

When you want to click a button on a web page during a test.
When you need to check if a text box is visible before typing.
When you want to get the text from a label or heading.
When you want to reuse the same web element in many tests without repeating code.
When you want to keep your test code clean and easy to update if the page changes.
Syntax
Selenium Python
class PageClassName:
    def __init__(self, driver):
        self.driver = driver
        self.element_name = (By.LOCATOR_TYPE, 'locator_value')

Use tuples with By to define locators clearly.

Keep locators as instance variables to reuse them easily.

Examples
This example shows locators by ID, NAME, and CSS selector in a login page class.
Selenium Python
from selenium.webdriver.common.by import By

class LoginPage:
    def __init__(self, driver):
        self.driver = driver
        self.username_input = (By.ID, 'username')
        self.password_input = (By.NAME, 'password')
        self.login_button = (By.CSS_SELECTOR, 'button.login')
Here, locators use XPath and class name to find elements on the home page.
Selenium Python
from selenium.webdriver.common.by import By

class HomePage:
    def __init__(self, driver):
        self.driver = driver
        self.search_box = (By.XPATH, '//input[@type="search"]')
        self.submit_button = (By.CLASS_NAME, 'submit-btn')
Sample Program

This test script uses a page class with element locators to enter username and password, then click login. It prints a success message if no errors occur.

Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options

class LoginPage:
    def __init__(self, driver):
        self.driver = driver
        self.username_input = (By.ID, 'username')
        self.password_input = (By.NAME, 'password')
        self.login_button = (By.CSS_SELECTOR, 'button.radius')

    def enter_username(self, username):
        self.driver.find_element(*self.username_input).send_keys(username)

    def enter_password(self, password):
        self.driver.find_element(*self.password_input).send_keys(password)

    def click_login(self):
        self.driver.find_element(*self.login_button).click()

# Setup Chrome driver (assuming chromedriver is in PATH)
options = Options()
options.add_argument('--headless')  # Run browser in headless mode
service = Service()
driver = webdriver.Chrome(service=service, options=options)

try:
    driver.get('https://the-internet.herokuapp.com/login')
    login_page = LoginPage(driver)
    login_page.enter_username('testuser')
    login_page.enter_password('password123')
    login_page.click_login()
    print('Test passed: Login actions performed successfully')
except Exception as e:
    print(f'Test failed: {e}')
finally:
    driver.quit()
OutputSuccess
Important Notes

Use the * operator to unpack locator tuples when calling find_element.

Keep locators in one place to make maintenance easier if the page changes.

Use meaningful variable names for locators to understand what element they represent.

Summary

Element locators in a page class help find web elements clearly and reuse them.

Locators are stored as tuples with By strategies and values.

This approach keeps test code clean, simple, and easy to maintain.

Practice

(1/5)
1. What is the main purpose of using element locators in a page class in Selenium Python?
easy
A. To find web elements clearly and reuse them easily
B. To write complex test logic inside the page class
C. To store test data separately from the test scripts
D. To execute browser commands directly

Solution

  1. Step 1: Understand the role of element locators

    Element locators help identify web elements on a page so tests can interact with them.
  2. Step 2: Recognize the benefit of using a page class

    Storing locators in a page class allows easy reuse and keeps code clean.
  3. Final Answer:

    To find web elements clearly and reuse them easily -> Option A
  4. Quick Check:

    Element locators = reuse and clarity [OK]
Hint: Locators in page class = find elements + reuse [OK]
Common Mistakes:
  • Confusing locators with test data storage
  • Thinking page class runs browser commands
  • Assuming locators hold test logic
2. Which of the following is the correct way to define a locator for a button with id 'submit' in a Selenium page class?
easy
A. submit_button = By('id', 'submit')
B. submit_button = By.ID('submit')
C. submit_button = ('id', submit)
D. submit_button = (By.ID, 'submit')

Solution

  1. Step 1: Recall the correct locator tuple format

    Locators are tuples with By strategy and string value, e.g., (By.ID, 'value').
  2. Step 2: Check each option's syntax

    submit_button = (By.ID, 'submit') uses (By.ID, 'submit'), which is correct. Others use wrong syntax or missing quotes.
  3. Final Answer:

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

    Locator tuple = (By.ID, 'value') [OK]
Hint: Locator = (By.<STRATEGY>, 'value') tuple [OK]
Common Mistakes:
  • Using By.ID('submit') instead of tuple
  • Missing quotes around 'submit'
  • Using wrong tuple structure
3. Given the locator login_button = (By.CSS_SELECTOR, 'button.login') in a page class, what will driver.find_element(*login_button) do?
medium
A. Cause a syntax error because of unpacking
B. Find the first button element with class 'login' on the page
C. Find all button elements with class 'login' on the page
D. Find an element by tag name 'button.login'

Solution

  1. Step 1: Understand the locator tuple and unpacking

    The locator is a tuple (By.CSS_SELECTOR, 'button.login'). Using * unpacks it into two arguments.
  2. Step 2: Know what find_element does

    find_element returns the first matching element, not all elements.
  3. Final Answer:

    Find the first button element with class 'login' on the page -> Option B
  4. Quick Check:

    find_element + CSS selector = first match [OK]
Hint: find_element finds first match, unpack locator tuple [OK]
Common Mistakes:
  • Confusing find_element with find_elements
  • Thinking unpacking causes syntax error
  • Misunderstanding CSS selector as tag name
4. You have this locator in your page class: search_box = (By.NAME, 'q'). Your test code uses driver.find_element(search_box) and fails. What is the error and how to fix it?
medium
A. Error: Missing unpacking operator '*'. Fix: Use driver.find_element(*search_box)
B. Error: Wrong locator type. Fix: Change By.NAME to By.ID
C. Error: Locator value is incorrect. Fix: Change 'q' to 'search'
D. Error: find_element cannot use tuples. Fix: Use string locator only

Solution

  1. Step 1: Identify the cause of failure

    driver.find_element expects two arguments, but passing a tuple without unpacking sends one argument.
  2. Step 2: Apply the correct fix

    Use the unpacking operator * to pass locator as separate arguments: driver.find_element(*search_box).
  3. Final Answer:

    Error: Missing unpacking operator '*'. Fix: Use driver.find_element(*search_box) -> Option A
  4. Quick Check:

    Unpack locator tuple with * [OK]
Hint: Always unpack locator tuple with * in find_element [OK]
Common Mistakes:
  • Not using * causes TypeError
  • Changing locator type unnecessarily
  • Assuming locator value is wrong
5. You want to create a page class locator for a link with text 'Home' that may appear as either an <a> tag or a <button> tag. Which locator is best to find it reliably?
hard
A. home_link = (By.LINK_TEXT, 'Home')
B. home_link = (By.CSS_SELECTOR, 'a.home, button.home')
C. home_link = (By.XPATH, "//a[text()='Home'] | //button[text()='Home']")
D. home_link = (By.ID, 'home')

Solution

  1. Step 1: Understand the locator requirements

    The element can be either an <a> or <button> with text 'Home', so locator must cover both tags.
  2. Step 2: Evaluate locator options

    home_link = (By.XPATH, "//a[text()='Home'] | //button[text()='Home']") uses XPath with OR (|) to match either tag by exact text, which is reliable. home_link = (By.LINK_TEXT, 'Home') only works for <a> tags. home_link = (By.CSS_SELECTOR, 'a.home, button.home') uses classes which may not exist. home_link = (By.ID, 'home') uses ID which is not given.
  3. Final Answer:

    home_link = (By.XPATH, "//a[text()='Home'] | //button[text()='Home']") -> Option C
  4. Quick Check:

    XPath OR matches multiple tags [OK]
Hint: Use XPath OR (|) to match multiple tag types [OK]
Common Mistakes:
  • Using LINK_TEXT misses button tags
  • Using CSS selectors without classes
  • Assuming ID exists without confirmation
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