Selenium WebDriver: Locating Web Elements with XPath contains() Function
Learn to use XPath's `contains()` function for flexible and robust web element location in Selenium WebDriver. This guide explains how to locate elements based on partial attribute values, making your tests more resilient to changes in webpage HTML.
Locating Web Elements in Selenium: Using XPath contains()
Introduction to XPath contains()
XPath (XML Path Language) is a powerful query language for selecting nodes within an XML document (HTML is a type of XML). The `contains()` function in XPath provides a flexible way to locate elements based on an attribute whose value includes a specific substring. This is particularly useful when you know only part of an attribute's value, making your locators more robust to changes in the webpage’s HTML.
XPath contains() Syntax
The basic syntax is:
//*[contains(@attribute_name, 'substring')]
This selects any element (//*
) where the specified attribute (e.g., `id`, `class`, `name`) contains the given substring
. The substring doesn't need to be at the beginning or end; it can appear anywhere within the attribute's value.
Example: Locating a Search Box Using contains()
Let's say you have a search input field on a webpage and you know that the ID contains "search". The exact ID might be something like "searchBox123", but you don't know the complete ID. Assume this (simplified) HTML (replace with the actual HTML from your target webpage):
<input type="text" id="searchBox_2024" />
An XPath expression using `contains()` would be:
//*[contains(@id, 'search')]
This XPath will select the input element because its `id` attribute contains the substring "search".
Using contains() in Selenium (Illustrative)
(Illustrative example; adapt this code to your specific Selenium framework and testing environment. Remember to include appropriate error handling in production code. The code would typically use `driver.findElement(By.xpath(...))` to locate the element. Replace the example XPath and URL with your actual values.)
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome() #Or your preferred WebDriver
driver.get("https://www.example.com/myform") #Replace with your URL
search_box = driver.find_element(By.XPATH, "//*[contains(@id, 'search')]")
search_box.send_keys("My Search Term")
search_box.submit()
driver.quit()
(The output will depend on the website's response to the search. The important part is that the script successfully finds the element.)