---
title: "How to Use XPath Contains: A Simple Guide with Examples"
description: "Learn what the XPath contains function is and how to use it for selecting web elements for web scraping, automation, testing, or other tasks requiring XPath expressions."
url: "https://iproyal.com/blog/xpath-contains-guide/"
---

- [EN - English](https://iproyal.com/)
   
  [中文 - Chinese](https://iproyal.cn/)

[Book a Demo](https://iproyal.com/request-a-demo/) [Create Account](https://dashboard.iproyal.com/register/) [Create Account](https://dashboard.iproyal.com/register/) [Login](https://dashboard.iproyal.com/login/) [Login](https://dashboard.iproyal.com/login/)

[Book a Demo](https://iproyal.com/request-a-demo/)

[Back to blog](https://iproyal.com/blog/)

# How to Use XPath Contains: A Simple Guide with Examples

[Eugenijus Denisov](https://iproyal.com/blog/authors/eugenijus-denisov/)

[Last updated - July 21, 2025 ‐ 6 min read](https://iproyal.com/blog/authors/eugenijus-denisov/)

[Tutorials](https://iproyal.com/blog/category/tutorials/)

## Key Takeaways

- XPath *contains* is used to find partial attribute or text values for locating web elements for various browser automation projects.

- The contains function in XPath can be used to replace CSS selectors.

- The contains function takes two arguments and returns a *True* value when there is at least a partial match.

- Using class attributes and AND or OR XPath expressions can help to select dynamic elements better.

- Combining absolute and relative XPath with the *contains&#x20;*&#x66;unction can save time when using web scraping templates.

XML Path Language (XPath for short) is **a query language allowing you to navigate to or select various nodes or node-sets in an XML or HTML document.&#x20;**&#x49;t might sound somewhat complex, but in practice, it’s simply used to find elements based on their attribute values or text content.

XPath is often used as an [alternative to CSS selectors ](https://iproyal.com/blog/xpath-vs-css-selectors/), and the *contains()* function is often cited as one of the advantages when comparing XPath and CSS selectors. **It’s one of the most used XPath functions in various web scraping, testing, and browser automation tasks.**

## What Is XPath *Contains* and Why Use It?

XPath *contains* is a function within the XPath expressions list to **select all the elements whose attribute values or text content partially match the argument&#x20;**&#x69;n the *contains()* function.

Unlike other XPath functions, **it can find partial attribute values to locate web elements&#x20;**&#x72;ather than requiring an exact match.

CSS selectors may be simpler for dynamic attributes like IDs or class names that change with each page load. However, **the *contains* function allows finding dynamic elements with XPath queries instead.**

**It is particularly useful for partial text or attribute matches when you don’t know the full value.&#x20;**&#x54;he XPath *contains* function is also handy when dealing with inconsistent web page markups where attribute values or text vary slightly, but enough to make other functions inapplicable.

**These scenarios occur quite often when web scraping or performing other web automation tasks with tools like [Selenium ](https://iproyal.com/blog/web-scraping-with-selenium-and-python/).&#x20;**&#x49;t makes the XPath *contains* function a versatile tool for many essential tasks.

## XPath Contains Syntax

The *contains()* function takes **two arguments&#x20;**&#x61;s a string in such a form:

```xml
contains(arg1, arg2)
```

The first argument is what you are looking for - an attribute, text, or other node content. The second argument is what you are searching for. **The function will return the value *True* if there is at least a partial match and *False* if there isn't.&#x20;**&#x48;ere's the **full *contains()* function syntax within the XPath expression&#x20;**&#x74;o find any element with the *tagname* that has an attribute containing *value:*

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

It's sometimes more useful to use the *contains* function **by looking for a partial text match to select elements.&#x20;**&#x54;he syntax doesn't change much:

```xml
//tagname[contains(text(), 'SomePartialText')]
```

If the web page doesn't define class elements consistently, **you can use the *contains* function to find partial text matches shown to the user.&#x20;**&#x49;n this case, the word *button* will locate anchor buttons.

```xml
//a[contains(text(), 'button')]
```

As with all XPath expressions, **it's important to avoid a few common mistakes&#x20;**&#x74;hat make working with XPath syntax difficult:

- XPath string values use single quotes ('), so if the string itself uses an apostrophe, it breaks the syntax, and double quotes or the *concat()* function is needed.
- Web pages often use extra spaces or tabs in text that XPath doesn't automatically delete. In such cases, the *normalize-space()* function is needed to locate web elements.
- The function *text()* does not match text inside child tags, only the text directly in the element. To deal with such cases of nesting, use a dot (.) to select all descendant text.
- In some cases, you might need to select elements based on the surrounding context. XPath axes allow you to navigate between nodes in the XML/HTML tree nodes. Use XPath axes to apply the *contains()* function to related nodes (parents, siblings, or ancestors) as well.
- Xpath *contains* is case-sensitive. Using one of the following literal strings - ‘button’ or ‘Button’ - will provide different results.

## How to Use Contains in XPath for Classes and Attributes

The examples given previously only explain basic XPath syntax. In a real-world scenario, **buttons are unlikely to even partially contain the word 'Button' for users.**

**Even class names might vary slightly&#x20;**&#x77;ith variations like *button\_primary,* *nav\_button,* *home\_button,* or similar. All of them might be selected by using an XPath query for class attributes that contain the word 'Button' in them.

```xml
//a[contains(@class, 'button')]
```

Such XPath expressions are especially useful for dynamic class attributes, where class names are generated automatically in an HTML or XML document, such as *button\_123,* *button\_124,* *button\_125,* etc. However, **their efficiency depends on the class naming pattern predictability.**

Adding *AND* or *OR* XPath expressions can further enhance how you select web page elements with dynamic classes and attributes. For example, **when you want elements that meet more than one condition or have multiple possible values.**

Using *OR* will select elements when any of the class names or attribute values match.

```xml
//a[contains(@class, 'button_primary') or contains(@class, 'nav_button')]
```

Using *AND* will select elements only when both classes are matched in the XML or HTML document.

```xml
//a[contains(@class, 'button') and contains(@class, 'primary')]
```

## Absolute vs. Relative XPath With Contains

**XPath expressions that outline location paths for a specific element from the root of the XML or HTML document are called absolute XPaths.&#x20;**&#x54;hey start with */* and are an easy-to-understand hierarchical way for selecting elements, but the absolute path breaks when something is modified.

Dynamic elements are frequently modified in a web page, so only relative XPaths (also known as dynamic XPaths) will work. We already used examples starting with *//,* which notes a relative XPath. **Absolute and relative XPaths can be combined when you know the structure, but some flexibility for dynamic elements is still needed.**

```xml
/html/body/div[3]/section/div[2]//a[contains(@class, 'button')]
```

The first part uses absolute XPath by specifying the location from the root of the document. The last part applies relative XPath, which contains the function to match any anchor that is in the 'button' class. **In practice, using relative XPath with *contains* is most common.**

**Combining them is most useful when you plan to use web scraping templates or other pre-written code.&#x20;**&#x4B;nowing how to combine absolute and relative XPaths can save time, as websites often share common layout structures.

## Using XPath Contains in Selenium (Python)

Selenium and other browser automation tools present some of the most common use cases for the XPath *contains* function. Selenium is free to use, so **you can start your web scraping, browser automation, testing, or other tasks right away.**

Here are three common examples using the *text()* function, *@class,* and *@href* attributes, which are commonly used with XPath *contains* instead of CSS selectors. **Be sure to first install the *Selenium* and *webdriver-manager* libraries if you want to run the code below.**

```python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import time

# Set up the Chrome driver
service = Service(ChromeDriverManager().install()) 
driver = webdriver.Chrome(service=service)

# Open the web page
driver.get("https://iproyal.com/")

# Locate a button using class attribute (partial match)
button = driver.find_element(By.XPATH, "//a[contains(@class, 'button')]")

# Print result
print("Button text:", button.text)

# Pause to view the result, then quit
time.sleep(2)
driver.quit()
```

```python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import time

# Set up the Chrome driver
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)

# Open the web page
driver.get("https://iproyal.com/")

# Locate a button using visible text (partial match)
button = driver.find_element(By.XPATH, "//a[contains(text(), 'button')]")

# Print result
print("Found button with text:", button.text)

# Pause to view result, then quit
time.sleep(2)
driver.quit()
```

```python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import time

# Set up the Chrome driver
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)

# Open the web page
driver.get("https://iproyal.com/")

# Locate a link or button using part of its href
button = driver.find_element(By.XPATH, "//a[contains(@href, 'button')]")

# Print result
print("Found link with href:", button.get_attribute("href"))

# Pause to view result, then quit
time.sleep(2)
driver.quit()
```

**Note that it all depends on the website you’re scraping.&#x20;**&#x57;e’re only using IPRoyal as an example, which currently has no buttons that provide data with the code above.

## Conclusion

This covers the basics of using the *contains* function in XPath for web scraping and related web development or automation tasks. Although it is somewhat more complex than using CSS selectors, it provides greater control in cases where web page structure is crucial.

[Create Account](https://dashboard.iproyal.com/)

[Author](https://iproyal.com/blog/authors/eugenijus-denisov/)

[Eugenijus Denisov](https://iproyal.com/blog/authors/eugenijus-denisov/)

[Lead Backend Developer](https://iproyal.com/blog/authors/eugenijus-denisov/)

With over a decade of experience under his belt, Eugenijus has worked on a wide range of projects - from LMS (learning management system) to large-scale custom solutions for businesses and the medical sector. Proficient in PHP, Vue.js, Docker, MySQL, and TypeScript, Eugenijus is dedicated to writing high-quality code while fostering a collaborative team environment and optimizing work processes. Outside of work, you’ll find him running marathons and cycling challenging routes to recharge mentally and build self-confidence.

[Learn More About Eugenijus Denisov ](https://iproyal.com/blog/authors/eugenijus-denisov/)[Meet all Writers](https://iproyal.com/blog/authors/)

Share on

### In This Article

- [What Is XPath \*Contains\* and Why Use It?](https://iproyal.com/blog/xpath-contains-guide/#What-Is-XPath-*Contains*-and-Why-Use-It)
- [XPath Contains Syntax](https://iproyal.com/blog/xpath-contains-guide/#XPath-Contains-Syntax)
- [How to Use Contains in XPath for Classes and Attributes](https://iproyal.com/blog/xpath-contains-guide/#How-to-Use-Contains-in-XPath-for-Classes-and-Attributes)
- [Absolute vs. Relative XPath With Contains](https://iproyal.com/blog/xpath-contains-guide/#Absolute-vs.-Relative-XPath-With-Contains)
- [Using XPath Contains in Selenium (Python)](https://iproyal.com/blog/xpath-contains-guide/#Using-XPath-Contains-in-Selenium-\(Python\))
- [Conclusion](https://iproyal.com/blog/xpath-contains-guide/#Conclusion)

Ready to get started?

[Register now](https://dashboard.iproyal.com/register/)

Data News in Your Inbox

No spam whatsoever, just pure data gathering news, trending topics and useful links. Unsubscribe anytime.

No spam. Unsubscribe anytime.

## Related articles

[View all](https://iproyal.com/blog/category/tutorials/)

[Tutorials](https://iproyal.com/blog/the-most-common-payment-processing-obstacles-and-solutions-for-saas-companies/)

## [The Most Common Payment Processing Obstacles and Solutions for SaaS Companies](https://iproyal.com/blog/the-most-common-payment-processing-obstacles-and-solutions-for-saas-companies/)

[Here are the most common payment processing obstacles SaaS companies face and the solution that helped us focus on growth and our services!](https://iproyal.com/blog/the-most-common-payment-processing-obstacles-and-solutions-for-saas-companies/)

[August 8, 2022](https://iproyal.com/blog/the-most-common-payment-processing-obstacles-and-solutions-for-saas-companies/)

[3 min read](https://iproyal.com/blog/the-most-common-payment-processing-obstacles-and-solutions-for-saas-companies/)

[Tutorials](https://iproyal.com/blog/easy-programmatic-seo-with-wordpress/)

## [Easy Programmatic SEO with WordPress](https://iproyal.com/blog/easy-programmatic-seo-with-wordpress/)

[Our fourth and final entry in the pSEO series explains how to combine programmatic SEO with WordPress using plugins or code snippets.](https://iproyal.com/blog/easy-programmatic-seo-with-wordpress/)

[March 30, 2023](https://iproyal.com/blog/easy-programmatic-seo-with-wordpress/)

[10 min read](https://iproyal.com/blog/easy-programmatic-seo-with-wordpress/)

[Tutorials](https://iproyal.com/blog/api-for-dummies-the-coders-and-no-coders-guide/)

## [API for Dummies — The Coder’s and No-coder’s Guide](https://iproyal.com/blog/api-for-dummies-the-coders-and-no-coders-guide/)

[Learn API basics with this guide for coders and non-coders. Discover the different components of an API call.](https://iproyal.com/blog/api-for-dummies-the-coders-and-no-coders-guide/)

[June 1, 2023](https://iproyal.com/blog/api-for-dummies-the-coders-and-no-coders-guide/)

[11 min read](https://iproyal.com/blog/api-for-dummies-the-coders-and-no-coders-guide/)
