XPath Practice: Mastering XPath Expressions for Effective Web Automation using Contains(), Text(), Starts-With() Function

Test Your Skills with this Fun and Interactive Game

Home->Practice 3

HTML Source document
          <span class="sub-text">
          <p>Contact US</p>
          <p id="p1" class="para">Para 1</p>
          <div class="container">
           <p id="p2" class="para" style="left:252px;">Para 2</p>
           <p id="p3" class="para" style="width:117px;">Para 3</p>
           <p id="p4" class="para" style="height:24px;">Para 4</p>
XPath Exercise 3

Q1. Find Contact US using Text()

Q2. Find Contact US using Contains()

Q3. Find Contact US using Starts-With()

Q4. Find Para 1 using ID attribute

Q5. Find Para 1 using Class attribute

Q6. Find Para 1 using ID and Class attribute

Q7. Find all Para inside the DIV tag

Q8. Find Para 2 using Style attribute

Q9. Find Para 3 using Style attribute

Q10. Find Para 4 using Style attribute

Q11. Find Para 2 and 3 together

Q12. Find Para 3 and 4 together

Q13. Find All Para

XPath O/P

Enter XPath Input here:   

XPath Tips and Syntax For This Page Exercise :

Using Contains()

Contains() is a method used to identify an element that changes dynamically and when we are familiar with some part of the attribute value of that element.

//HTML tag[contains(@attribute_name,'attribute_value')]



Here are a few examples to demonstrate how to use the Contains() in Selenium:

WebDriver driver = new FirefoxDriver();
WebElement link = driver.findElement(By.xpath("//a[contains(text(), 'Link Text')]"));

Using text()

The text() function in XPath can be used to select the text content of an element.


Using starts-with()


// Navigate to a website
// Select all elements whose class attribute starts with "example-"
List elements = driver.findElements(By.xpath("//*[starts-with(@class, 'example-')]"));

Using ID, Class, Style Attribute


Using AND

//input[@id='Email' and @name='Email']
//*[@id='Email' and @name='Email']
We would love to hear your thoughts, suggestions, concerns or problems with anything so we can improve!