Understanding XPath and CSS Selectors in Selenium

๐Ÿ” Understanding XPath and CSS Selectors in Selenium

In Selenium, locators are used to find and interact with web elements. Two powerful locators are:


XPath (XML Path Language)


CSS Selectors (Cascading Style Sheets)


๐Ÿ“Œ 1. XPath

✅ What is XPath?

XPath is a syntax for navigating XML documents, and it works well with HTML. It allows you to locate elements based on tag names, attributes, text content, position, etc.


✅ Types of XPath:

Absolute XPath: Starts from the root /html/body/div[1]/div[2]/span


Relative XPath: More flexible //div[@class='example']


✅ Common XPath Examples:

python

Copy

Edit

# By tag and attribute

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


# By text

driver.find_element(By.XPATH, "//button[text()='Login']")


# Using contains()

driver.find_element(By.XPATH, "//div[contains(@class, 'active')]")


# By position

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

๐ŸŽฏ 2. CSS Selectors

✅ What is a CSS Selector?

CSS Selectors use HTML element types, classes, IDs, and attributes to locate elements—similar to how CSS styles elements.


✅ Common CSS Selector Examples:

python

Copy

Edit

# By ID

driver.find_element(By.CSS_SELECTOR, "#username")


# By class

driver.find_element(By.CSS_SELECTOR, ".login-form")


# By attribute

driver.find_element(By.CSS_SELECTOR, "input[name='email']")


# Tag + class

driver.find_element(By.CSS_SELECTOR, "button.submit-btn")


# Nested elements

driver.find_element(By.CSS_SELECTOR, "div.container > ul > li.active")

๐Ÿค” XPath vs CSS Selector: Which One to Use?

Feature XPath CSS Selector

Syntax More powerful, but verbose Cleaner and faster

Text matching ✅ Yes (text() supported) ❌ Not directly supported

DOM traversal (upward) ✅ Yes ❌ No

Speed Slightly slower Faster in most browsers

Readability Depends on complexity Often more readable


Use CSS Selectors when: Speed and readability matter.

Use XPath when: You need to find elements by text or need advanced matching.


๐Ÿงช Python Example with Both:

python

Copy

Edit

from selenium import webdriver

from selenium.webdriver.common.by import By


driver = webdriver.Chrome()

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


# Using XPath

element_xpath = driver.find_element(By.XPATH, "//input[@id='search']")


# Using CSS Selector

element_css = driver.find_element(By.CSS_SELECTOR, "#search")


element_xpath.send_keys("XPath Test")

element_css.clear()

element_css.send_keys("CSS Selector Test")


driver.quit()

Would you like a cheatsheet PDF or practice web pages to try XPath and CSS Selectors?

Learn Selenium JAVA Training in Hyderabad

Read More

How to Handle Browser Pop-ups and Alerts in Selenium with Java

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?