Bird
Raised Fist0
Selenium Javatesting~10 mins

Choosing XPath vs CSS strategy in Selenium Java - Test Execution Compared

Choose your learning style10 modes available
Test Overview

This test opens a webpage and tries to find a button using both XPath and CSS selectors. It verifies that the button is clickable and visible, demonstrating the difference in locating elements with XPath and CSS strategies.

Test Code - JUnit with Selenium WebDriver
Selenium Java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Duration;

public class XPathVsCssTest {
    WebDriver driver;
    WebDriverWait wait;

    @BeforeEach
    public void setUp() {
        driver = new ChromeDriver();
        wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    }

    @Test
    public void testButtonWithXPathAndCss() {
        driver.get("https://example.com/testpage");

        // Locate button using XPath
        WebElement buttonByXPath = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@id='submit-btn']")));
        assertTrue(buttonByXPath.isDisplayed(), "Button located by XPath should be visible");

        // Locate button using CSS Selector
        WebElement buttonByCss = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("button#submit-btn")));
        assertTrue(buttonByCss.isDisplayed(), "Button located by CSS should be visible");

        // Click the button using CSS selector
        buttonByCss.click();
    }

    @AfterEach
    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
}
Execution Trace - 8 Steps
StepActionSystem StateAssertionResult
1Test starts and Chrome browser opensChrome browser window is open and ready—PASS
2Navigates to https://example.com/testpagePage loads with a button having id 'submit-btn'—PASS
3Waits until button located by XPath //button[@id='submit-btn'] is clickableButton is present and clickable on the pageVerify button located by XPath is displayedPASS
4Asserts button located by XPath is visibleButton is visibleassertTrue(buttonByXPath.isDisplayed())PASS
5Waits until button located by CSS selector button#submit-btn is clickableButton is present and clickable on the pageVerify button located by CSS is displayedPASS
6Asserts button located by CSS selector is visibleButton is visibleassertTrue(buttonByCss.isDisplayed())PASS
7Clicks the button located by CSS selectorButton click triggers expected action—PASS
8Test ends and browser closesBrowser window is closed—PASS
Failure Scenario
Failing Condition: Button with id 'submit-btn' is not found or not clickable within 10 seconds
Execution Trace Quiz - 3 Questions
Test your understanding
Which locator strategy is used to find the button first in the test?
ACSS Selector
BXPath
CID locator
DClass name
Key Result
Use explicit waits with clear locator strategies like XPath or CSS selectors to reliably find elements. Choose CSS selectors for speed and simplicity when possible, XPath for complex queries.

Practice

(1/5)
1. Which locator strategy is generally faster and simpler for selecting elements in Selenium Java?
easy
A. Name Locator
B. XPath
C. CSS Selector
D. ID Locator

Solution

  1. Step 1: Understand locator speed

    ID locators are the fastest and simplest because they directly map to unique element IDs in the DOM.
  2. Step 2: Compare with CSS Selector

    CSS selectors are fast and flexible but generally slightly slower than ID locators.
  3. Final Answer:

    ID Locator -> Option D
  4. Quick Check:

    ID Locator = Fastest and simplest [OK]
Hint: Use ID locator for fastest and simplest element selection [OK]
Common Mistakes:
  • Thinking XPath is always faster
  • Confusing CSS with ID locator
  • Assuming XPath is simpler syntax
2. Which of the following is a correct CSS selector syntax to select all <div> elements with class active?
easy
A. div.active
B. //div[@class='active']
C. div#active
D. div[class='active']

Solution

  1. Step 1: Identify CSS selector for class

    In CSS, a dot (.) before a class name selects elements with that class, so div.active selects divs with class active.
  2. Step 2: Check other options

    //div[@class='active'] is XPath syntax, not CSS. div#active selects div with id 'active', not class. div[class='active'] is a CSS attribute selector but less common than the dot notation for class.
  3. Final Answer:

    div.active -> Option A
  4. Quick Check:

    CSS class selector = div.active [OK]
Hint: Use dot (.) for class in CSS selectors [OK]
Common Mistakes:
  • Using XPath syntax as CSS
  • Confusing id (#) with class (.)
  • Using attribute selector incorrectly
3. Given the HTML snippet:
<ul>
  <li class='item'>One</li>
  <li class='item'>Two</li>
  <li class='item'>Three</li>
</ul>

What will the following Selenium Java code return?
List<WebElement> elements = driver.findElements(By.cssSelector("ul > li.item"));
System.out.println(elements.size());
medium
A. Throws exception
B. 1
C. 3
D. 0

Solution

  1. Step 1: Analyze CSS selector

    The selector ul > li.item selects all li elements with class 'item' that are direct children of ul.
  2. Step 2: Count matching elements

    There are 3 li elements with class 'item' directly under ul, so the list size is 3.
  3. Final Answer:

    3 -> Option C
  4. Quick Check:

    3 matching elements = 3 [OK]
Hint: Count elements matching CSS selector directly under parent [OK]
Common Mistakes:
  • Confusing descendant (space) with child (>) selector
  • Assuming only one element matches
  • Expecting exception on valid selector
4. You wrote this XPath locator in Selenium Java:
By.xpath("//div[@id='main']//a[text()='Click Here']")

But your test fails to find the element. What is a likely reason?
medium
A. The XPath syntax is invalid and causes an error
B. The element text has extra spaces or different casing
C. CSS selector should be used instead of XPath here
D. The locator should use single slash '/' instead of double '//'

Solution

  1. Step 1: Check XPath syntax

    The XPath syntax is correct and valid for selecting an a element with exact text 'Click Here' inside a div with id 'main'.
  2. Step 2: Consider text matching issues

    XPath text() matches exact text. If the actual element text has extra spaces or different letter case, it won't match.
  3. Final Answer:

    The element text has extra spaces or different casing -> Option B
  4. Quick Check:

    Exact text match fails if text differs [OK]
Hint: Check exact text match in XPath for spaces or case [OK]
Common Mistakes:
  • Assuming XPath syntax error without checking text
  • Switching to CSS without reason
  • Changing slashes incorrectly
5. You need to select the third <li> element inside a <ul> with dynamic classes and no IDs. Which locator strategy is best and why?
hard
A. CSS selector using :nth-child(3) pseudo-class for simplicity and speed
B. XPath using position() function for precise element location
C. ID locator because it is always fastest
D. Name locator because it works for list items

Solution

  1. Step 1: Analyze element attributes

    The li elements have dynamic classes and no IDs, so ID locator is not possible.
  2. Step 2: Compare XPath and CSS for position

    XPath position() can select the third li, but CSS :nth-child(3) is simpler and faster for this case.
  3. Final Answer:

    CSS selector using :nth-child(3) pseudo-class for simplicity and speed -> Option A
  4. Quick Check:

    Use CSS :nth-child for simple positional selection [OK]
Hint: Use CSS :nth-child for fast, simple positional element selection [OK]
Common Mistakes:
  • Choosing XPath unnecessarily for simple position
  • Assuming ID locator always exists
  • Using Name locator for non-form elements
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