🎯 Selenium Locators in Python – Complete Guide
Locators are the foundation of Selenium automation. They are used to identify and interact with web elements like buttons, input fields, links, dropdowns, etc. Without locators, Selenium cannot perform any action on the web page.
📌 What are Locators?
Locators are methods used to find elements on a web page. They help Selenium identify HTML elements uniquely so that actions like click, send keys, and validation can be performed.
- To identify elements uniquely
- To perform actions on web elements
- To validate UI elements
- To build stable automation scripts
🆔 ID Locator
ID locator is the fastest and most reliable locator in Selenium.
driver.find_element(By.ID, "username")
📝 Name Locator
Name locator is used when elements have a name attribute.
driver.find_element(By.NAME, "password")---
🏷 Class Name Locator
Used when elements have a class attribute.
driver.find_element(By.CLASS_NAME, "login-btn")⚠ Note: Avoid using dynamic class names. ---
🔖 Tag Name Locator
Used to locate elements based on HTML tag name.
driver.find_elements(By.TAG_NAME, "a")---
🔗 Link Text & Partial Link Text
Used for hyperlinks (<a> tags).
driver.find_element(By.LINK_TEXT, "Login") driver.find_element(By.PARTIAL_LINK_TEXT, "Log")---
🎨 CSS Selector
CSS Selector is powerful and faster than XPath in many browsers.
#id driver.find_element(By.CSS_SELECTOR, "#username") .class driver.find_element(By.CSS_SELECTOR, ".login-btn") tag.class driver.find_element(By.CSS_SELECTOR, "button.submit") attribute driver.find_element(By.CSS_SELECTOR, "input[name='email']")---
🧭 XPath (Absolute vs Relative)
Absolute XPath
/html/body/div[1]/form/input[1]❌ Not recommended (breaks easily)
Relative XPath
//input[@id='username']✅ Recommended (stable and flexible) ---
🧠 XPath Functions
contains(): //input[contains(@id,'user')] starts-with(): //input[starts-with(@id,'user')] text(): //button[text()='Login']---
✅ Best Practices for Writing XPath
- Avoid absolute XPath
- Use unique attributes
- Prefer relative XPath
- Avoid dynamic attributes
- Use contains() for dynamic values
- Write readable XPath
- Keep XPath short and clean
- Test XPath in browser dev tools
Mastering locators is the most important skill in Selenium automation. Good locator strategy makes automation scripts stable, maintainable, and reliable. Strong XPath and CSS selector knowledge is the backbone of professional automation frameworks.
No comments:
Post a Comment