---
title: "XPath Cheat Sheet: Complete Guide with Examples"
description: "Master XPath with this essential cheat sheet. Learn to create quick and effective queries for your data needs."
url: "https://iproyal.com/blog/xpath-cheat-sheet/"
---

- [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/)

# XPath Cheat Sheet: Complete Guide with Examples

[Marijus Narbutas](https://iproyal.com/blog/authors/marijus-narbutas/)

[Last updated - October 9, 2025 ‐ 5 min read](https://iproyal.com/blog/authors/marijus-narbutas/)

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

## Key Takeaways

- XPath is a query language for selecting elements in XML and HTML, commonly used in web scraping and automation tools like Selenium and Scrapy.

- This XPath cheat sheet includes core syntax, axes, predicates, and functions - presented in a quick-reference format with practical examples.

- You'll also learn common mistakes to avoid, best practices, and real-world XPath expressions to improve the accuracy and stability of your queries.

**XPath is a query language used to navigate and extract data from XML and HTML documents.&#x20;**&#x44;evelopers use it widely in web scraping, automated testing, and other tasks. You’ll find it in tools like Scrapy, Selenium, and inside many browser dev tools.

It works across all major browsers and supports different versions. **Most real-world use cases rely on XPath 1.0.&#x20;**&#x46;eatures from later versions, such as XPath 2.0 or 3.0, often aren’t supported by tools or browsers.

## XPath Cheat Sheet: Core Syntax and Functions

Here is a cheat sheet for some of the **most popular and common XPath expressions.**

| Syntax | Description | Example |
| - | - | - |
| // | Selects nodes anywhere in the document relative to the current node | //div |
| / | Selects from root node | /html/body/div |
| @ | Selects attributes | //a\[@href] |
| . | Refers to current node | .//span |
| .. | Goes to parent of current node | .. |
| \* | Matches any element | //\* |
| text() | Selects text node children of the current element | //p/text() |
| contains() | Returns true if the first string contains the second string | //div\[contains(@class, ‘item’)] |
| normalize-space() | Cleans up whitespace | //div\[normalize-space(text())=’Login’] |
| substring-before() | Gets text before a string | substring-before(‘item\_123’, ‘\_’) |
| substring-after() | Gets text after a string | substring-after(‘item\_123’, ‘\_’) |
| string-length() | Returns the number of characters in a string | string-length(text()) > 10 |

### Selectors & Navigation

XPath selectors let you move through nodes and match elements. **//div&#x20;**&#x66;inds all **`<div>`&#x20;**&#x74;ags in the document relative to the current node. **It’s one of the most common XPath expression patterns.&#x20;**&#x55;se **”.”&#x20;**&#x61;nd **”..”&#x20;**&#x74;o stay near the current node. Combine these with filters to get more specific results.

### Axes

XPath axes let you navigate the tree structure. Here’s how it works:

- **child::&#x20;**&#x73;elects direct children.
- **parent::&#x20;**&#x6D;oves to the parent.
- **ancestor::&#x20;**&#x63;limbs up the tree.
- **ancestor-or-self::&#x20;**&#x69;ncludes the current node and its ancestors.
- **descendant::&#x20;**&#x67;rabs all nested elements.
- **following-sibling::&#x20;**&#x73;elects siblings after the current node.
- **preceding-sibling&#x20;**&#x73;elects preceding siblings before the current node.
- **self::.&#x20;**&#x72;efers to the current node itself.

The *following-sibling* axis is very useful when you want to grab elements that appear on the same level. The *ancestor-or-self* axis selects the current node and all of its ancestors up the hierarchy, which is useful when you need to match or verify conditions up the tree.

### Predicates & Filters

**Predicates help filter your XPath expression.&#x20;**&#x54;hey use square brackets like this:

```javascript
//div[@id='menu'][2]
```

You can also combine conditions:

```javascript
//div[@class='item' and text()='Save']
```

Filtering helps create a robust XPath locator that is less prone to breaking.

### Operators

Some useful operators include:

- **=.&#x20;**&#x45;qual to.
- **!=.&#x20;**&#x4E;ot equal.
- **<, <=, >, >=&#x20;**&#x43;omparisons.
- **and, or.&#x20;**&#x4C;ogical checks.

Mix them to build relative XPath patterns.

### Functions

Use functions to fine-tune results:

- **contains()&#x20;**&#x66;or partial matches.
- **starts-with()&#x20;**&#x74;o match beginnings.
- **normalize-space()&#x20;**&#x63;leans up messy whitespace.
- **string-length()&#x20;**&#x6D;easures length.
- **substring-before()&#x20;**&#x67;ets part of the string before a given substring.
- **substring-after()&#x20;**&#x67;rabs part of the string after a given string.
- **position()&#x20;**&#x66;inds indexed elements.

## XPath Examples in Practice

Let’s use XPath expression **examples that work in tools like Chrome DevTools or Selenium.**

### Basic Selection

```javascript
//h1
//div/p
```

*//h1* selects all *`<h1>`* elements. *`<//div/p>`* selects *`<p>`* elements that are direct children of *`<div>`.*

### Attribute Matching

```python
//input[@type='text']
//a[contains(@href, 'signup')]
```

**It finds elements by attribute.&#x20;**&#x59;ou’ll write these XPath locator types frequently.

### Structural Patterns

```javascript
//ul/li[1]
//table//tr/td[2]
```

Great for lists and tables. **However, don’t over-rely on index.&#x20;**&#x49;t’s fragile unless the structure is stable.

### Conditional Logic

```python
//button[@class='save' and normalize-space(text())='Submit']
//div[string-length(text()) > 5]
```

These are smarter XPath expression patterns. **They filter by content or text length.**

## XPath Best Practices

To make sure that you have the best possible experience with XPath, **follow these best practices:**

- Use relative XPaths (*//div\[@class='x']*) instead of absolute XPaths (*/html/body/.*)
- Chain conditions to target elements more reliably.
- Use *normalize-space()* to clean up whitespace issues.
- Avoid relying on element index unless the structure is stable.
- Test your XPath expression in browser dev tools: *$x('//div').*

You’ll notice that **XPath locator stability increases with chaining and logic.**

## Common XPath Mistakes to Avoid

Avoiding certain pitfalls using XPath will help you be more efficient with it. Here are some **mistakes people often make:**

- Using invalid or unsupported functions (especially from XPath 2.0/3.0).
- Over-relying on brittle absolute XPaths like */html/body/.*
- Not escaping special characters in attribute values.

**A fragile XPath expression can break your scraper or test rather quickly.**

## Conclusion

XPath gives you efficient methods to navigate XML and HTML documents. It’s great when you master its use. Practice with examples and tweak your own XPath locator inside DevTools.

Try using it with tools like Selenium, Scrapy, or browser dev tools to automate tasks. Remember, relative XPath keeps your code cleaner and more stable than absolute XPath.

Use this XPath cheat sheet whenever you’re stuck or unsure how to write a solid path.

## FAQ

How do I write a dynamic XPath that adapts to page changes?

Use relative XPath and avoid depending on exact indexes. Rely on text or class names instead. *//div\[contains(@class, 'section')]* generally works better than */html/body/div\[2].*

Can XPath select elements based on partial text or patterns?

Yes. Use *contains()* or *starts-with()* for node matching.

Can I use XPath in programming languages like Python or JavaScript?

Python supports XPath with libraries like *lxml.* In JavaScript, browsers support XPath with *$x()* or *document.evaluate().*

What’s the performance difference between XPath and CSS selectors?

CSS selectors are often faster and simpler. However, XPath expressions offer more flexibility, especially with XPath axes and advanced filtering.

How do I troubleshoot or debug a failing XPath expression?

Start by testing it in browser DevTools: *$x('//div').* Then simplify it. Check the current node or inspect *ancestor-or-self* and *preceding-sibling* relationships.

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

[Author](https://iproyal.com/blog/authors/marijus-narbutas/)

[Marijus Narbutas](https://iproyal.com/blog/authors/marijus-narbutas/)

[Senior Software Engineer](https://iproyal.com/blog/authors/marijus-narbutas/)

With more than seven years of experience, Marijus has contributed to developing systems in various industries, including healthcare, finance, and logistics. As a backend programmer who specializes in PHP and MySQL, Marijus develops and maintains server-side applications and databases, ensuring our website works smoothly and securely, providing a seamless experience for our clients. In his free time, he enjoys gaming on his PS5 and stays active with sports like tricking, running, and weight lifting.

[Learn More About Marijus Narbutas ](https://iproyal.com/blog/authors/marijus-narbutas/)[Meet all Writers](https://iproyal.com/blog/authors/)

Share on

### In This Article

- [XPath Cheat Sheet: Core Syntax and Functions](https://iproyal.com/blog/xpath-cheat-sheet/#XPath-Cheat-Sheet:-Core-Syntax-and-Functions)
- [XPath Examples in Practice](https://iproyal.com/blog/xpath-cheat-sheet/#XPath-Examples-in-Practice)
- [XPath Best Practices](https://iproyal.com/blog/xpath-cheat-sheet/#XPath-Best-Practices)
- [Common XPath Mistakes to Avoid](https://iproyal.com/blog/xpath-cheat-sheet/#Common-XPath-Mistakes-to-Avoid)
- [Conclusion](https://iproyal.com/blog/xpath-cheat-sheet/#Conclusion)
- [FAQ](https://iproyal.com/blog/xpath-cheat-sheet/#FAQ)

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/)
