Locating Elements in Selenium using ID, Name, Class, XPath, and CSS Selectors

Locating Elements in Selenium: ID, Name, Class, XPath, and CSS Selectors

In Selenium, locating elements on a webpage is one of the most essential tasks for writing automated tests or scripts. Selenium provides several ways to find HTML elements.


✅ 1. Locating by ID

Best for: Unique and simple elements.


python

Copy

Edit

element = driver.find_element(By.ID, "username")

✅ Fast and reliable if the ID is unique.


✅ 2. Locating by Name

Best for: Forms and inputs with a name attribute.


python

Copy

Edit

element = driver.find_element(By.NAME, "email")

⚠️ Not always unique — be cautious if multiple elements share the same name.


✅ 3. Locating by Class Name

Best for: Elements styled with a single class.


python

Copy

Edit

element = driver.find_element(By.CLASS_NAME, "login-button")

⚠️ Only works with a single class (not a string with multiple class names).


✅ 4. Locating by XPath

Best for: Complex or dynamic structures.


python

Copy

Edit

element = driver.find_element(By.XPATH, "//input[@type='submit']")

Can navigate the DOM with precision.


Use // for any level, / for direct children.


Supports complex conditions:


python

Copy

Edit

//div[@class='user' and @data-role='admin']

⚠️ Slower than CSS in many cases, and more verbose.


✅ 5. Locating by CSS Selector

Best for: Flexibility and performance.


python

Copy

Edit

element = driver.find_element(By.CSS_SELECTOR, "input[type='submit']")

Supports class, ID, attribute, pseudo-classes, etc.


Examples:


css

Copy

Edit

#login       /* by ID */

.btn-primary /* by class */

div > input  /* child selector */

✅ Generally faster and shorter than XPath.


🧪 Example in Python (Selenium)

python

Copy

Edit

from selenium import webdriver

from selenium.webdriver.common.by import By


driver = webdriver.Chrome()

driver.get("https://example.com")


# ID

driver.find_element(By.ID, "searchBox")


# Name

driver.find_element(By.NAME, "q")


# Class

driver.find_element(By.CLASS_NAME, "search-btn")


# XPath

driver.find_element(By.XPATH, "//input[@placeholder='Search']")


# CSS Selector

driver.find_element(By.CSS_SELECTOR, "input.search-input")

🧠 Tips for Choosing the Best Locator:

Strategy Use When... Speed Readability

ID ID is unique and available ✅ Fast ✅ Clear

Name Forms with unique name attributes ✅ Fast ✅ Clear

Class Name Simple, single-class elements ✅ Fast ✅ Clear

XPath Complex structure or dynamic elements ❌ Slower ❌ Verbose

CSS Selector No ID/class, need flexible targeting ✅ Fast ✅ Compact

Learn Selenium Python Training in Hyderabad

Visit Our Quality Thought Training in Hyderabad

Get Directions

Comments

Popular posts from this blog

Understanding Snowflake Editions: Standard, Enterprise, Business Critical

Why Data Science Course?

How To Do Medical Coding Course?