Worldscope

g) Using contains()

Palavras-chave:

Publicado em: 04/08/2025

Using `contains()` in Selenium XPath

The `contains()` function in XPath is a powerful tool for locating elements on a webpage based on partial text matches within their attributes or text content. This article explains how to effectively use `contains()` in Selenium to create more flexible and robust locators.

Fundamental Concepts / Prerequisites

Before diving into `contains()`, you should have a basic understanding of the following:

  • XPath: XPath (XML Path Language) is a query language for selecting nodes from an XML document. Selenium uses XPath to locate elements on a webpage.
  • Selenium WebDriver: Familiarity with Selenium WebDriver and its methods for interacting with web elements (e.g., `findElement()`).
  • HTML Structure: Understanding how HTML elements are structured and how to inspect them in a web browser.
  • Attributes: Understanding HTML attributes such as `id`, `class`, `name`, and `text`.

Implementation in Python with Selenium


from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service

# Setup Chrome WebDriver (adjust path if necessary)
service = Service(executable_path="/path/to/chromedriver")
driver = webdriver.Chrome(service=service)

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

# Example 1: Locate an element where the text contains "Example"
element1 = driver.find_element(By.XPATH, "//*[contains(text(), 'Example')]")
print(f"Element 1 text: {element1.text}")

# Example 2: Locate an element with an attribute that contains "link"
element2 = driver.find_element(By.XPATH, "//a[contains(@href, 'example')]")
print(f"Element 2 href: {element2.get_attribute('href')}")

# Example 3:  More specific - find a div containing certain text
element3 = driver.find_element(By.XPATH, "//div[contains(@class, 'container') and contains(text(), 'Some text')]")
print(f"Element 3 text: {element3.text}")


driver.quit()

Code Explanation

* from selenium import webdriver: Imports the Selenium WebDriver library. * from selenium.webdriver.common.by import By: Imports the `By` class, which is used to specify the type of locator (e.g., XPath). * driver = webdriver.Chrome(): Initializes a Chrome WebDriver instance. You may need to download chromedriver and specify the path. * driver.get("https://www.example.com"): Navigates the WebDriver to the specified URL. Replace with the URL you're testing. * element1 = driver.find_element(By.XPATH, "//*[contains(text(), 'Example')]"): This line finds the first element on the page whose text content contains the string "Example". `//*` selects any element, and `contains(text(), 'Example')` filters for elements where the text includes "Example". * element2 = driver.find_element(By.XPATH, "//a[contains(@href, 'example')]"): This line finds the first `` (anchor) element on the page whose `href` attribute contains the string "example". * element3 = driver.find_element(By.XPATH, "//div[contains(@class, 'container') and contains(text(), 'Some text')]"): Combines two `contains()` conditions within a single XPath query to find a `div` element. The `div`'s `class` attribute must contain 'container' AND its text content must contain 'Some text'. This improves specificity. * driver.quit(): Closes the browser window and terminates the WebDriver session.

Complexity Analysis

* Time Complexity: The time complexity of `contains()` in XPath largely depends on the structure of the HTML and the specific implementation of the XPath engine used by Selenium. In the worst-case scenario, where the `contains()` function needs to iterate through a large portion of the document to find a match, the complexity could approach O(n), where n is the number of nodes in the DOM. However, well-optimized XPath engines and specific XPath expressions (e.g., using more specific element types like `//a`) can significantly reduce the search space. * Space Complexity: The space complexity is relatively low and generally considered to be O(1), as it mainly involves storing the search string and references to the nodes being examined.

Alternative Approaches

While `contains()` is powerful, other approaches can be used depending on the specific scenario:

  • `starts-with()`: If you know the beginning of the text you're looking for, `starts-with()` can be used. This can sometimes be more efficient than `contains()` because it only needs to check the beginning of the string. The XPath would look like: `//a[starts-with(text(), 'Start of Text')]`.
  • `equals` (=): If you need an exact match for an attribute's value, use `=`. This will generally be faster than `contains()` as it performs a direct comparison. Example: `//div[@id='exactId']`
  • CSS Selectors: CSS selectors can sometimes be more efficient and easier to read than XPath, especially for simple attribute-based selections. For example, you could use `driver.find_element(By.CSS_SELECTOR, "a[href*='example']")` to achieve the same result as Example 2 above.

Conclusion

The `contains()` function is a valuable asset in Selenium for creating flexible and robust locators. It allows you to identify elements based on partial text matches, making your tests less brittle to minor changes in the application's UI. However, it's important to be aware of potential performance implications and consider alternative approaches like `starts-with()` or CSS selectors when appropriate. Using `contains()` effectively can significantly improve the maintainability and reliability of your Selenium tests.