Selenium + Python · Lesson 16 of 43

0/43 done

Module 16: Locators

16. Locating WebElements: By Strategies, CSS & Robust XPath

18 minlesson

Your task

Implement make_button_locator(button_text):

  1. Return (By.XPATH, f"//button[contains(normalize-space(), '{button_text}')]").

Write it in the editor, then press Check answer (Ctrl + Enter).

Locator Strategies via By

python
from selenium.webdriver.common.by import By

btn_id = (By.ID, "login-btn")
btn_css = (By.CSS_SELECTOR, "button[data-testid='submit']")
btn_xpath = (By.XPATH, "//button[contains(text(), 'Submit')]")

# XPath Axes:
user_delete_btn = (By.XPATH, "//tr[td[text()='Dhanu']]//button[@aria-label='Delete']")

Key Takeaways & Walkthrough Summary

Locators connect your test code to DOM elements. In Python Selenium, all search strategies use the By class. In this lesson, we prioritize robust IDs, CSS selectors, and dynamic XPath expressions over fragile absolute paths. Let's master locators!

Part of the Selenium + Python course (Selenium with Python). Practice this concept live in the Selenium Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

Why store locators as tuples (By.ID, 'foo') in Python?

Tuples can be easily unpacked into driver.find_element(*locator), which is standard in Python Page Object Models.

Ready? Solve the task in the editor

Use Check answer to mark it complete. Hints are there if you need them.

Python
Skip