Popular Searches
Popular Course Categories
Popular Courses

Contains()

XPath in Selenium

Contains() in XPath

The contains() function in XPath is used to locate web elements when only a part of an attribute value or text is known. It is especially useful for dynamic web applications where complete attribute values may change, but a stable portion of the value remains the same.

In Selenium automation, contains() is commonly used with XPath to locate buttons, links, input fields, messages, product names, table data, and other web elements. XPath and CSS selectors are included among the locator topics in JustAcademy's Selenium training curriculum. :contentReference[oaicite:0]{index=0}

For structured Selenium learning, visit JustAcademy Selenium Training. You can also explore the JustAcademy Course Demo Registration.


1. What is contains() in XPath?

The contains() function is an XPath function used for partial matching. Instead of requiring the complete value of an attribute or text, it searches for an element whose value contains the specified portion.

The basic idea is:

contains(value, 'partial value')

For example, suppose an element has the following HTML:

<button id="login_button_12345">Login</button>

The complete ID may change dynamically, but the word "login" remains stable. In this situation, contains() can be used:

//button[contains(@id,'login')]

This XPath searches for a button whose id attribute contains the value "login".


2. Why Use contains() in XPath?

Modern web applications frequently generate dynamic values for attributes such as id, class, name, href, and value. Using the complete attribute value may make an XPath fragile.

The contains() function allows automation testers to use a stable portion of the value.

  • Useful for dynamic web elements.
  • Supports partial attribute matching.
  • Supports partial text matching.
  • Can reduce dependency on changing attribute values.
  • Useful for buttons, links, forms, tables, and messages.
  • Can be combined with and and or conditions.
  • Can be combined with XPath axes.
  • Useful in Selenium automation frameworks.


3. Basic Syntax of contains()

The general syntax is:

contains(attribute, 'value')

When used with an XPath locator:

//tagname[contains(@attribute,'value')]

Example:

//input[contains(@id,'username')]

This searches for an input element whose id contains "username".


4. contains() with ID Attribute

ID is one of the most common attributes used with contains().

Consider this HTML:

<input id="username_12345" type="text">

If the numeric portion changes dynamically, an exact XPath such as:

//input[@id='username_12345']

may become invalid.

Instead, use:

//input[contains(@id,'username')]

This XPath can continue to work if the ID changes from username_12345 to username_67890, provided the stable portion remains "username".


5. contains() with Class Attribute

The contains() function can be used with class attributes when the class value contains a stable class name.

Example:

<button class="btn btn-primary login-button">Login</button>

XPath:

//button[contains(@class,'login-button')]

This identifies the button using the partial class value.


6. contains() with Name Attribute

Consider the following HTML:

<input name="user_login_123" type="text">

XPath:

//input[contains(@name,'user_login')]

This can be useful when the name attribute contains a dynamic suffix.


7. contains() with Placeholder

Placeholder text can also be used in an XPath.

Example:

<input placeholder="Enter your username here">

XPath:

//input[contains(@placeholder,'username')]

This searches for an input whose placeholder contains "username".


8. contains() with Value Attribute

The value attribute can also be searched partially.

<input type="submit" value="Login to Account">

XPath:

//input[contains(@value,'Login')]


9. contains() with Text

One of the most common uses of contains() is locating elements using partial visible text.

Example:

<button>Login to Your Account</button>

XPath:

//button[contains(text(),'Login')]

This XPath searches for a button whose text contains "Login".


10. Exact Text vs contains() Text

TechniqueXPathMatching
Exact Text//button[text()='Login']Only exact Login text
Partial Text//button[contains(text(),'Login')]Any button containing Login

For example, the XPath using text() may match:

//button[text()='Login']

But it may not match:

<button>Login to Account</button>

The contains() expression can match it:

//button[contains(text(),'Login')]


11. contains() with Links

Links often contain stable portions of visible text.

<a href="/products">View All Products</a>

XPath:

//a[contains(text(),'Products')]

Another example:

//a[contains(text(),'View All')]


12. contains() with Button Text

Buttons frequently contain dynamic or extended labels.

<button>Continue to Payment</button>

XPath:

//button[contains(text(),'Continue')]

Another example:

//button[contains(text(),'Payment')]


13. contains() with Headings

Headings can be located using partial text.

<h1>Welcome to Selenium Automation Training</h1>

XPath:

//h1[contains(text(),'Selenium')]

Another example:

//h1[contains(text(),'Automation Training')]


14. contains() with Labels

Labels can also be identified using partial text.

<label>Enter Your Email Address</label>

XPath:

//label[contains(text(),'Email')]


15. contains() with Paragraphs

Paragraphs containing a specific phrase can be located using contains().

<p>Your registration has been completed successfully.</p>

XPath:

//p[contains(text(),'registration')]


16. contains() with Error Messages

Error messages often contain additional dynamic information. Partial matching can be useful for validating them.

<div class="error">Error: Invalid username or password</div>

XPath:

//div[contains(text(),'Invalid username')]

Another example:

//div[contains(text(),'Error')]


17. contains() with Success Messages

Success messages can also be identified using partial text.

<div class="success">Order placed successfully. Order ID: 12345</div>

XPath:

//div[contains(text(),'Order placed successfully')]

The dynamic order ID does not need to be included in the XPath.


18. contains() with href Attribute

Links often contain dynamic URL parameters.

Example:

<a href="/product/details?id=12345">Product Details</a>

XPath:

//a[contains(@href,'/product/details')]

This can be useful when query parameters change dynamically.


19. contains() with Multiple Attributes

Multiple contains() conditions can be combined using the and operator.

//input[contains(@id,'username') and contains(@class,'form-control')]

This XPath searches for an input whose ID contains "username" and whose class contains "form-control".


20. contains() with OR Condition

The or operator can be used when more than one possible value is acceptable.

//button[contains(text(),'Login') or contains(text(),'Sign In')]

This can locate a button containing either "Login" or "Sign In".


21. Multiple contains() Conditions

Multiple contains() functions can be used together.

//button[contains(@class,'btn') and contains(@class,'primary') and contains(text(),'Submit')]

This expression checks multiple conditions on the same button.


22. contains() with Parent Relationship

contains() can be combined with XPath axes.

Example:

//span[contains(text(),'Login')]/parent::button

This identifies the button that contains a span with partial text "Login".


23. contains() with Child Elements

You can use contains() to identify a parent based on text inside a child.

//div[span[contains(text(),'Product')]]

This searches for a div containing a span whose text includes "Product".


24. contains() with Ancestor

The ancestor axis can be combined with contains().

//span[contains(text(),'Add to Cart')]/ancestor::div[contains(@class,'product')]

This can locate the product container associated with an Add to Cart element.


25. contains() with Following-Sibling

contains() can be useful when a label has partial text and its associated input is a sibling.

//label[contains(text(),'Username')]/following-sibling::input

Example:

<label>Enter Username</label>

<input type="text">


26. contains() in Tables

Tables frequently contain changing values. contains() can help locate rows using partial text.

<tr>

<td>John Smith</td>

<td>QA Automation Engineer</td>

</tr>

XPath:

//tr[td[contains(text(),'John')]]

This locates the table row containing a cell with text that includes "John".


27. contains() for Product Tables

Suppose a product table contains product names and statuses.

<tr>

<td>Samsung Galaxy Smartphone</td>

<td>Available</td>

</tr>

XPath:

//tr[td[contains(text(),'Samsung Galaxy')]]

To locate the status cell:

//tr[td[contains(text(),'Samsung Galaxy')]]/td[2]


28. contains() for E-Commerce Products

E-commerce applications are common examples of dynamic websites where contains() can be useful.

<div class="product-card">

<h2>Apple iPhone 17 Pro Max</h2>

<button class="add-cart-button">Add iPhone to Cart</button>

</div>

XPath for the product:

//h2[contains(text(),'iPhone')]

XPath for the button:

//button[contains(text(),'Add') and contains(text(),'Cart')]

XPath for the product card:

//div[contains(@class,'product-card') and .//h2[contains(text(),'iPhone')]]


29. contains() for Login Automation

Login applications may use different labels such as Login, Login Now, Sign In, or Sign In to Account.

Example:

<button>Login to Account</button>

XPath:

//button[contains(text(),'Login')]

For a dynamic ID:

//button[contains(@id,'login')]


30. contains() for Registration Forms

Registration forms may contain dynamic IDs and stable portions of attributes.

<input id="firstName_4582" placeholder="Enter First Name">

XPath:

//input[contains(@id,'firstName')]

Using placeholder:

//input[contains(@placeholder,'First Name')]


31. contains() for Dynamic IDs

Dynamic IDs are one of the most common situations where contains() is used.

Example:

<input id="input_user_839472">

Instead of:

//input[@id='input_user_839472']

Use:

//input[contains(@id,'input_user')]

If the dynamic portion changes while "input_user" remains stable, the XPath can still identify the element.


32. contains() for Dynamic Class Names

Modern frameworks may generate class names containing stable and dynamic portions.

Example:

<button class="MuiButton-root login-button-4821">Login</button>

XPath:

//button[contains(@class,'login-button')]

When using class attributes, make sure the selected partial value is sufficiently specific to avoid matching unintended elements.


33. contains() with normalize-space()

When whitespace may vary, contains() can be combined with normalize-space().

//button[contains(normalize-space(),'Login')]

Example:

<button>   Login to Account   </button>

The normalized text can be searched more reliably.


34. contains() with Dot Operator

The dot operator represents the string value of the current node and can include text from descendant elements.

Consider:

<button>

<span>Login</span>

</button>

A text-based XPath using contains() can be:

//button[contains(.,'Login')]

This can be useful when the visible text is inside nested elements.


35. contains(text()) vs contains(.)

ExpressionUse
contains(text(),'Login')Checks text nodes associated with the current element.
contains(.,'Login')Checks the string value of the current node, including descendant text.

Example:

//button[contains(text(),'Login')]

For nested text:

//button[contains(.,'Login')]


36. contains() with Dynamic Text

Suppose a page displays:

<div>Welcome John, your account is active</div>

The username may change dynamically.

Instead of matching the complete text, use:

//div[contains(text(),'your account is active')]

This focuses on the stable portion of the message.


37. contains() for Notifications

Notifications may contain changing values such as usernames, order numbers, or timestamps.

<div class="notification">Order #12345 has been shipped successfully</div>

XPath:

//div[contains(text(),'has been shipped successfully')]

The changing order number does not need to be included.


38. contains() for Shopping Cart Messages

<div>Product successfully added to your shopping cart</div>

XPath:

//div[contains(text(),'added to your shopping cart')]


39. contains() with Selenium Java

In Selenium Java, the XPath expression can be passed to By.xpath().

WebDriver driver = new ChromeDriver();

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

driver.findElement(By.xpath("//button[contains(text(),'Login')]")).click();


40. contains() with ID in Selenium Java

WebElement username = driver.findElement(

    By.xpath("//input[contains(@id,'username')]")

);

username.sendKeys("admin");


41. contains() with Class in Selenium Java

WebElement loginButton = driver.findElement(

    By.xpath("//button[contains(@class,'login-button')]")

);

loginButton.click();


42. contains() with Explicit Wait

Dynamic web elements may not be immediately available. An explicit wait can be combined with a contains() XPath.

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

WebElement button = wait.until(

    ExpectedConditions.elementToBeClickable(

        By.xpath("//button[contains(text(),'Login')]")

    )

);

button.click();


43. contains() with Visibility Wait

For elements that need to become visible:

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

WebElement message = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.xpath("//div[contains(text(),'Success')]")

    )

);


44. Complete Selenium Example

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 java.time.Duration;

 

public class ContainsXPathExample {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

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

 

        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

 

        WebElement loginButton = wait.until(

            ExpectedConditions.elementToBeClickable(

                By.xpath("//button[contains(text(),'Login')]")

            )

        );

 

        loginButton.click();

 

        WebElement username = driver.findElement(

            By.xpath("//input[contains(@id,'username')]")

        );

 

        username.sendKeys("admin");

 

        driver.quit();

    }

}


45. contains() in Page Object Model

In a Page Object Model framework, contains() XPath expressions can be stored as reusable locators.

public class LoginPage {

    private WebDriver driver;

 

    private By usernameField =

        By.xpath("//input[contains(@id,'username')]");

 

    private By loginButton =

        By.xpath("//button[contains(text(),'Login')]");

 

    public LoginPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void enterUsername(String username) {

        driver.findElement(usernameField).sendKeys(username);

    }

 

    public void clickLogin() {

        driver.findElement(loginButton).click();

    }

}


46. contains() with Multiple Elements

If multiple elements contain the same partial text, contains() may return multiple matches.

Example:

<button>Login</button>

<button>Login as Admin</button>

<button>Login as Guest</button>

The following XPath:

//button[contains(text(),'Login')]

can match all three buttons.

Therefore, the XPath may need an additional condition.

//button[contains(text(),'Login as Admin')]


47. contains() with Index

If multiple elements match and the intended element is known by position, an index can be used.

(//button[contains(text(),'Login')])[1]

Second matching element:

(//button[contains(text(),'Login')])[2]

Indexes should be used carefully because changes to the DOM can change element positions.


48. contains() with last()

The last() function can be used when the last matching element is required.

(//button[contains(text(),'Login')])[last()]


49. contains() for Navigation Menus

Navigation items can be identified using partial text.

<nav>

<a>Home</a>

<a>Products and Services</a>

<a>Contact Us</a>

</nav>

XPath:

//nav//a[contains(text(),'Products')]

Another example:

//nav//a[contains(text(),'Contact')]


50. contains() for Dropdown Options

Options can be located using partial text.

<option>United States of America</option>

XPath:

//option[contains(text(),'United States')]

For standard HTML select elements, Selenium's Select class can be more appropriate when selecting by visible text.


51. contains() for Radio Buttons

Radio button labels can be located using contains().

<label>

<input type="radio" name="gender" value="male">

Male Candidate

</label>

Example XPath:

//label[contains(text(),'Male Candidate')]/input

The exact XPath should be adjusted according to the actual DOM structure.


52. contains() for Checkboxes

Checkboxes may be associated with labels containing descriptive text.

<label>

<input type="checkbox">

Accept Terms and Conditions

</label>

Possible XPath:

//label[contains(text(),'Accept Terms')]/input


53. contains() for Dynamic Web Applications

Dynamic applications may generate changing IDs, classes, and other attributes. JustAcademy's Selenium curriculum specifically includes locating elements with XPath and CSS selectors as well as handling dynamic elements and synchronization. :contentReference[oaicite:1]{index=1}

Example:

<button id="submit_839291">Submit Order</button>

Dynamic XPath:

//button[contains(@id,'submit')]

If the ID later becomes submit_938271, the same XPath can still work as long as "submit" remains stable.


54. contains() in AJAX Applications

AJAX-based applications can update page content without a full page reload. In such situations, contains() can identify dynamically inserted elements while explicit waits handle synchronization.

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement success = wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.xpath("//div[contains(text(),'successfully')]")

    )

);


55. contains() in React Applications

React applications can generate dynamic class names and IDs. A stable portion of an attribute or visible text can sometimes be used with contains().

//button[contains(@class,'login') and contains(text(),'Login')]

The locator should always be validated against the actual DOM because framework-generated structures can vary.


56. contains() in Angular Applications

Angular applications may contain generated attributes and dynamic DOM content.

//input[contains(@id,'email')]

Or:

//button[contains(text(),'Submit')]

When elements are loaded asynchronously, an appropriate Selenium wait should be used.


57. contains() with Shadow DOM

XPath cannot automatically cross a Shadow DOM boundary in the same way it navigates a normal DOM tree. If the target element exists inside a Shadow DOM, the automation approach must first access the shadow root and then locate elements within the appropriate context.

Therefore, simply writing:

//button[contains(text(),'Login')]

may not work when the button is inside a separate shadow root.


58. contains() with Frames and iFrames

If the target element is inside an iframe, Selenium must switch to the iframe before attempting to locate the element.

driver.switchTo().frame("loginFrame");

 

WebElement button = driver.findElement(

    By.xpath("//button[contains(text(),'Login')]")

);

 

button.click();

 

driver.switchTo().defaultContent();


59. contains() with Multiple Conditions and Attributes

A robust locator can combine partial attribute values with text.

//button[contains(@id,'login') and contains(@class,'primary') and contains(text(),'Login')]

This can be more specific than using only one contains() condition.


60. contains() vs equals Matching

MethodExamplePurpose
Exact Attribute//input[@id='username']Matches the complete attribute value
Partial Attribute//input[contains(@id,'username')]Matches part of the attribute value
Exact Text//button[text()='Login']Matches exact text
Partial Text//button[contains(text(),'Login')]Matches part of the text


61. Common Mistakes with contains()

  • Using a partial value that is too generic.
  • Matching multiple elements unintentionally.
  • Using contains() when exact matching would be more appropriate.
  • Ignoring whitespace in text matching.
  • Using text() when the target text is inside a child element.
  • Forgetting that XPath text comparisons can be case-sensitive.
  • Using an unstable portion of a dynamic attribute.
  • Not validating the XPath in browser DevTools.
  • Using indexes unnecessarily.
  • Ignoring synchronization for dynamically loaded elements.


62. Bad contains() Example

Consider:

//button[contains(@class,'btn')]

If many buttons use the class "btn", this XPath may match several elements.

A more specific XPath could be:

//button[contains(@class,'btn') and contains(@class,'login')]

Or:

//button[contains(text(),'Login')]

The best locator depends on the actual DOM structure and which values are stable.


63. How to Test contains() XPath in Chrome DevTools

Chrome DevTools can be used to verify an XPath before using it in Selenium.

  1. Open the application in Chrome.
  2. Right-click the target element.
  3. Select Inspect.
  4. Open the Console tab.
  5. Use the $x() function.
  6. Enter the XPath.
  7. Check the returned elements.

Example:

$x("//button[contains(text(),'Login')]")

For a dynamic ID:

$x("//input[contains(@id,'username')]")


64. Practical Example: Login Page

<div class="login-form">

<input id="user_12345" placeholder="Enter Username">

<input id="pass_67890" placeholder="Enter Password">

<button id="login_45678">Login to Account</button>

</div>

Username:

//input[contains(@id,'user')]

Password:

//input[contains(@id,'pass')]

Login button:

//button[contains(@id,'login')]

Login button using text:

//button[contains(text(),'Login')]


65. Practical Example: E-Commerce Application

<div class="product-card-123">

<h2>Laptop Pro 15</h2>

<span class="price">$999</span>

<button class="cart-btn-789">Add Laptop to Cart</button>

</div>

Product:

//h2[contains(text(),'Laptop Pro')]

Price:

//span[contains(@class,'price')]

Add to Cart:

//button[contains(@class,'cart-btn') and contains(text(),'Add')]

Product container:

//div[contains(@class,'product-card') and .//h2[contains(text(),'Laptop Pro')]]


66. Practical Example: Table Automation

<table>

<tr>

<td>John Smith</td>

<td>QA Engineer</td>

<td>Active</td>

</tr>

<tr>

<td>David Kumar</td>

<td>Developer</td>

<td>Active</td>

</tr>

</table>

Find John's row:

//tr[td[contains(text(),'John')]]

Find John's role:

//tr[td[contains(text(),'John')]]/td[2]

Find John's status:

//tr[td[contains(text(),'John')]]/td[3]


67. Practical Example: Dynamic Notification

<div class="notification">

Hello John, your order #98765 has been successfully placed.

</div>

Instead of matching the entire dynamic message:

//div[text()='Hello John, your order #98765 has been successfully placed.']

Use a stable portion:

//div[contains(text(),'has been successfully placed')]


68. Practical Example: Registration Success

<div class="alert-success">

Registration completed successfully for user 12345.

</div>

XPath:

//div[contains(@class,'alert-success') and contains(text(),'Registration completed')]


69. Practical Example: Search Results

<div class="search-result">

<h2>Selenium Automation Course</h2>

<a href="/course/selenium">View Course Details</a>

</div>

Course heading:

//h2[contains(text(),'Selenium Automation')]

Course link:

//a[contains(text(),'Course Details')]


70. Best Practices for contains()

  • Use a stable portion of the attribute or text.
  • Make the partial value as specific as reasonably possible.
  • Combine contains() with other conditions when necessary.
  • Use text-based contains() when visible text is stable.
  • Use contains(@id,...) for dynamic IDs with stable prefixes or portions.
  • Use normalize-space() when whitespace can vary.
  • Use contains(.,...) for nested text when appropriate.
  • Check whether the XPath returns one element or multiple elements.
  • Use explicit waits for dynamically loaded elements.
  • Validate XPath expressions in DevTools.
  • Avoid unnecessary indexes.
  • Keep XPath readable and maintainable.


71. Advantages of contains()

  • Supports partial matching.
  • Useful for dynamic attributes.
  • Useful for dynamic text.
  • Can make locators more flexible.
  • Can reduce dependency on complete dynamic values.
  • Can be combined with other XPath functions.
  • Works well with Selenium's By.xpath() locator.
  • Useful for modern dynamic web applications.


72. Limitations of contains()

  • It may return multiple elements if the partial value is too generic.
  • A changing visible text can make a text-based locator unstable.
  • Case differences can affect matching.
  • Incorrect use with nested elements can produce unexpected results.
  • Using contains() on a common class name may match many elements.
  • It does not solve synchronization problems by itself.
  • It does not automatically cross iframe or Shadow DOM boundaries.


73. contains() vs Other XPath Functions

FunctionExamplePurpose
contains()contains(@id,'user')Partial matching
starts-with()starts-with(@id,'user')Prefix matching
text()text()='Login'Exact text matching
normalize-space()normalize-space()='Login'Whitespace normalization
last()[last()]Last matching element


74. Interview Questions on contains()

Q1. What is contains() in XPath?

contains() is an XPath function used for partial matching of attribute values or text.

Q2. Why is contains() used in Selenium?

It is commonly used when an element has dynamic or partially known attributes or text.

Q3. What is the syntax of contains()?

//tagname[contains(@attribute,'value')]

Q4. How do you locate a button containing Login?

//button[contains(text(),'Login')]

Q5. How do you locate an input whose ID contains username?

//input[contains(@id,'username')]

Q6. Can contains() be used with class?

Yes.

//button[contains(@class,'login')]

Q7. Can contains() be combined with and?

Yes.

//button[contains(@id,'login') and contains(text(),'Login')]

Q8. Can contains() be used with text?

Yes. A common form is:

//button[contains(text(),'Login')]

Q9. What is the difference between contains(text(),'Login') and contains(.,'Login')?

contains(text(),'Login') checks text nodes of the selected element, while contains(.,'Login') checks the string value of the current node and can include descendant text.

Q10. What is the main risk of using contains()?

A generic partial value can match multiple elements, so the locator should be specific enough to identify the intended element.


75. Quick Reference Table

RequirementXPath
Dynamic ID//input[contains(@id,'username')]
Dynamic Class//button[contains(@class,'login')]
Dynamic Name//input[contains(@name,'user')]
Partial Placeholder//input[contains(@placeholder,'email')]
Partial Value//input[contains(@value,'Submit')]
Partial Text//button[contains(text(),'Login')]
Partial Link Text//a[contains(text(),'Products')]
Dynamic Href//a[contains(@href,'product')]
Nested Text//button[contains(.,'Login')]
Multiple Conditions//button[contains(@id,'login') and contains(text(),'Login')]
OR Condition//button[contains(text(),'Login') or contains(text(),'Sign In')]
Table Row//tr[td[contains(text(),'John')]]
Parent//span[contains(text(),'Login')]/parent::button
Following Sibling//label[contains(text(),'Username')]/following-sibling::input


76. Key Points to Remember

  • contains() is used for partial matching in XPath.
  • It can be used with attributes such as id, class, name, href, placeholder, and value.
  • It can also be used with visible text.
  • contains() is especially useful for dynamic attribute values.
  • contains(text(),'value') is useful for partial text matching.
  • contains(.,'value') can be useful when text exists inside descendant elements.
  • Multiple contains() conditions can be combined using and or or.
  • contains() can be combined with XPath axes such as parent, ancestor, and following-sibling.
  • Always verify that the locator identifies the intended element.
  • Use explicit waits when the element is dynamically loaded.
  • Do not choose an overly generic partial value.
  • Test complex XPath expressions in Chrome DevTools using $x().


77. Conclusion

The contains() function is one of the most useful XPath techniques for Selenium automation. It allows testers to locate elements using a stable portion of an attribute or text instead of depending on the complete value. This makes it particularly useful for dynamic IDs, class names, URLs, placeholders, button labels, messages, product information, and table data.

A good contains() XPath should use a meaningful and stable partial value. When necessary, it can be combined with attributes, text conditions, normalize-space(), XPath axes, and multiple logical conditions to create a more specific locator.

JustAcademy's Selenium training curriculum includes Selenium WebDriver, element locating with XPath and CSS selectors, dynamic elements, synchronization, TestNG, framework development, and practical automation projects. :contentReference[oaicite:2]{index=2}

Learn more through JustAcademy Selenium Training or register for the JustAcademy Course Demo.

whatsapp