XPath Cheat Sheet With Examples, Syntax, Selectors, and Functions

programming10 min read

Learn XPath syntax, selectors, functions, and axes with clear examples. Complete XPath cheat sheet for Selenium testing, web scraping, and DOM parsing.

Introduction

XPath stands for XML Path Language. Developers use XPath to locate elements inside XML and HTML documents. XPath plays a key role in Selenium automation testing, web scraping, and DOM navigation. Search engines receive large volumes of queries such as "XPath cheat sheet", "XPath selectors list", and "XPath examples".

This guide provides a structured XPath reference. You learn syntax, selectors, axes, functions, and real examples. Each section focuses on practical usage. Tables and code examples support quick learning.

Readers who work with Selenium, Scrapy, or DOM parsing benefit from this guide.


XPath Cheat Sheet With Examples and Syntax


What is XPath

XPath refers to a query language used to locate nodes inside XML or HTML documents.

Developers use XPath to:

  • Locate elements inside a webpage
  • Extract structured data
  • Automate browser testing
  • Parse XML files
  • Perform web scraping

Example XML structure

<html> <body> <div class="container"> <h1>Title</h1> <a href="/home">Home</a> </div> </body> </html>

XPath allows selection of elements from this structure.

Example XPath

//h1

This query selects every h1 element.


XPath Syntax Basics

XPath follows a path based structure similar to a file system.

Structure example

/html/body/div

Each part represents a node.

Basic XPath syntax elements

SymbolMeaning
/Select root node
//Select nodes anywhere
.Current node
..Parent node
@Attribute selector

Examples

XPathResult
//divSelect every div element
//aSelect every link
//*Select all elements
//h1Select all h1 elements

Search engines receive high search volume for queries such as "XPath syntax example".


XPath Selectors Cheat Sheet

Selectors help locate elements using tag names or attributes.

XPath SelectorDescription
//divSelect all div elements
//pSelect paragraph elements
//a[@href]Select links with href attribute
//*Select all nodes
//inputSelect input elements

Example

//a[@href]

Result

Select every anchor element containing an href attribute.


XPath Attribute Selectors

Attribute selection remains one of the most used XPath techniques.

Syntax

//tag[@attribute="value"]

Examples

XPath ExpressionDescription
//input[@type="text"]Select text input
//div[@class="header"]Select header container
//button[@id="submit"]Select submit button

Example code

//input[@name="username"]

Developers search queries such as "XPath attribute selector example".


XPath Text Functions

XPath supports functions for text based filtering.

Common text functions

FunctionPurpose
text()Match exact text
contains()Match partial text
starts-with()Match prefix text

Examples

Exact text match

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

Contains text

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

Starts with text

//div[starts-with(text(),"Welcome")]

These expressions help locate dynamic elements.


XPath Axes Explained

Axes define the relationship between nodes.

Common XPath axes

AxisMeaning
parentSelect parent node
childSelect child node
ancestorSelect ancestors
descendantSelect children and grandchildren
following-siblingSelect next sibling

Examples

Parent selection

//div/parent::section

Child selection

//div/child::p

Sibling selection

//h2/following-sibling::p

Axes support complex DOM traversal.


XPath Position Functions

Position based selection helps select specific elements.

Common functions

FunctionDescription
position()Current index
last()Last element

Examples

First element

//li[1]

Second element

//li[2]

Last element

//li[last()]

Position based selection appears frequently in scraping tasks.


XPath Logical Operators

XPath supports logical filtering using operators.

Common operators

OperatorPurpose
andCombine conditions
orEither condition
not()Negation

Examples

AND condition

//input[@type="text" and @name="email"]

OR condition

//button[@id="login" or @id="submit"]

NOT condition

//div[not(@class)]

Logical filtering improves selector accuracy.


XPath Examples for Selenium

Automation testers rely on XPath selectors.

Example Selenium code in Python

driver.find_element(By.XPATH,"//input[@id='username']")

Example Selenium code in Java

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

Common Selenium XPath examples

TaskXPath
Locate input//input
Locate button//button
Locate link text//a[text()="Home"]

Automation frameworks rely on XPath for locating dynamic elements.


XPath Examples for Web Scraping

Web scraping tools extract page content using XPath.

Example using Python Scrapy

response.xpath("//h1/text()").get()

Extract links

response.xpath("//a/@href").getall()

Extract product titles

response.xpath("//div[@class='product']/h2/text()").getall()

Scraping frameworks process thousands of pages using XPath selectors.


XPath vs CSS Selectors

Both methods locate elements inside HTML documents.

Comparison table

FeatureXPathCSS Selector
Select parent nodeYesNo
Select text nodesYesNo
Syntax complexityHigherLower
Browser performanceSlightly slowerFaster

CSS selectors dominate frontend selection. XPath works well for scraping and testing.


Advanced XPath Examples

Advanced expressions handle dynamic elements.

Example 1

//*[contains(@class,"btn")]

Select elements with partial class match.

Example 2

//div[.//span]

Select div containing span child.

Example 3

//a[contains(@href,"product")]

Select links containing product in URL.

Advanced queries support accurate data extraction.


Common XPath Mistakes

Developers often create fragile selectors.

Common issues

  • Absolute paths break easily
  • Dynamic IDs change frequently
  • Excessively long expressions slow selection

Bad example

/html/body/div[2]/div[1]/h1

Better approach

//div[@class="title"]/h1

Short expressions maintain stability.


Complete XPath Cheat Sheet

Quick reference table.

TaskXPath
Select element//tag
Select attribute//@attribute
Select attribute value//tag[@attribute="value"]
Select first element//tag[1]
Select last element//tag[last()]
Select contains text//tag[contains(text(),"value")]
Select child//parent/child
Select descendant//parent//child

Axes and Navigation

SelectorExplanation
elementTarget node by its tag name (e.g., div, a)
*Matches any single node (functions as a wildcard)
. or selfPoints to the current node
[n]Retrieves the n-th node (index begins at 1)
/Select a child node relative to its parent
//Targets any descendant regardless of depth levels
./ or .//Specifies a relative path from the current context
..Targets the immediate parent node
ancestor::Retrieves all ancestor nodes (parent, grandparent, etc.)
preceding::Finds nodes that appear before the given context (above)
following::Finds nodes that appear after the given context (below)
preceding-sibling::Select siblings appearing before the present node
following-sibling::Select siblings appearing after the present node

Logical Operators

SelectorExplanation
|Merges multiple selector paths (union of node-sets)
orCombines multiple alternative conditions
andDemands all specified conditions to be true (fulfilled)

Attribute Matching

SelectorExplanation
@attributeTargets elements by attribute name
text()Extracts text data inside a node
[]Used to filter nodes based on rules (predicate)
[][]Filters using multiple element predicates
[node[]]Evaluates using nested element predicate
[a=b]Ensures a value matches precisely
[a>b], [a<b]Performs numeric equality checks using (greater, lesser) signs

Functions

SelectorExplanation
name()Extract the name of a seleted node
not(A)Reverse A
number(A)Converts the value into a numeric type
contains(A, B)Checks if string B exists inside A
matches(...) or re:test(...)Tests expression against a regular expression
tokenize(value, pattern)Divides a text string based on a regex pattern
lower-case(A)Convert into lowercase
starts-with(A, B)Checks if A begins with B
ends-with(A, B)Checks if A ends with B
concat(*args)Merges multiple string inputs into a single combined output
substring(str, start, len)Extracts a specific portion of characters from a string
substring-before(str, sep)Retrieves characters preceding a specified separator
substring-after(str, sep)Retrieves characters succeeding a specified separator
normalize-space(A)Trims surrounding whitespace and collapses internal spaces
count(A)Count total of matching nodes
position()Get the index position of the node in the current set
last()Get the final node inside a sequence
string-length(A)Get the total length of the passed text

Common Patterns

SelectorExplanation
//a/@hrefRetrieves the href attribute of all anchors in the page
//img/@srcExtracts all the image source in the page
//text()Collects all text under a node
//child::*/text()Gathers strictly the text of the direct children
[contains(concat(' ',normalize-space(@class),' '),' myclass ')]check exact class name (myclass) with space-seperated list of classes
[preceding::div[.="One"] and following::div[.="Two"]]Finds specific nodes situated exactly between two nodes

Non-standard Functions

SelectorExplanation
re:test(x, expr, flags)Executes regex evaluation; specific to libraries like Scrapy, Parsel, and lxml

Bookmark this section for quick lookup.


XPath Best Practices

Follow these rules for stable selectors.

  • Prefer relative XPath
  • Use attributes for selection
  • Avoid absolute paths
  • Keep expressions short
  • Test selectors inside browser DevTools

Example stable XPath

//button[@type="submit"]

Automation projects maintain reliability using stable selectors.


FAQ About XPath

What is XPath used for

XPath locates elements inside XML or HTML documents. Developers apply XPath in Selenium testing, web scraping, and XML parsing.

How to find XPath in Chrome

Steps

  • Open Chrome DevTools
  • Inspect element
  • Right click element
  • Copy XPath

Which performs faster: XPath or CSS

CSS selectors perform faster in browsers. XPath supports complex queries such as parent traversal.

Does Selenium support XPath

Selenium supports XPath through By.XPATH locator strategy.

Example

driver.find_element(By.XPATH,"//input[@name='email']")

Key Takeaways

XPath helps locate elements inside structured documents. XPath selectors work well for automation testing and data extraction. Developers rely on attribute filters, text functions, and axes for precise selection. Structured selectors maintain reliability during automation workflows.

Related Posts