Glossary
XPath
XPath (XML Path Language) is a query language for selecting nodes in XML and HTML documents by their position in the tree, their attributes or their text, widely used in web scraping, test automation and XML processing.
XPath, short for XML Path Language, is a query language for selecting nodes in XML and HTML documents. An XPath expression describes a route through the document tree, such as "every link inside the main navigation" or "the cell next to the one that says Total", and returns the nodes at the end of that route.
XPath was published by the W3C in 1999 as part of the XML family of standards. Version 1.0 is the one built into web browsers and most scraping libraries; later versions (2.0, 3.0 and 3.1) add types, sequences and many more functions and are mainly used in XML tooling. In web scraping and browser automation, XPath sits alongside CSS selectors as one of the two standard ways to point at elements in the DOM, and it is the stronger of the two when you need to match on text or walk up the tree.
How XPath expressions work
An XPath expression is a series of steps separated by slashes. Each step moves from the current set of nodes to a new set, and each can carry a filter in square brackets, called a predicate. The expression “//table[@id=’rates’]/tbody/tr” starts anywhere in the document, finds tables whose id attribute is rates, steps into their tbody and returns every row.
A single slash at the start means the path begins at the document root, so “/html/body/div” names an exact chain from the top. A double slash means “at any depth”, so “//div” finds every div in the document. Attributes are addressed with an at sign, as in “@href”, and text nodes with “text()”.
Steps move along axes. The default axis is child, which is why “tr/td” means the td children of a row, but XPath has others: descendant, parent, ancestor, following-sibling, preceding-sibling and more. Axes are what let XPath go places CSS cannot, such as from a label up to its containing row and then across to the next cell.
Predicates filter each step. They can test attributes, position or text, and they can contain whole sub-paths. “//li[3]” is the third list item among its siblings, “//a[contains(@href, ‘pdf’)]” is every link whose address contains pdf, and “//tr[td[1]=’Total’]” is every row whose first cell says Total.
Expressions you will use
The table covers the forms that come up most often in scraping and testing.
Expression | Selects |
|---|---|
//h2 | Every h2 element anywhere in the document |
//div[@class=’price’] | Divs whose class attribute is exactly price |
//div[contains(@class, ‘price’)] | Divs whose class attribute contains the text price |
//a/@href | The href attribute of every link |
//p/text() | The direct text nodes of every paragraph |
//button[normalize-space()=’Checkout’] | Buttons whose visible text, trimmed, is Checkout |
//label[text()=’Email’]/following-sibling::input[1] | The first input after the label Email |
//span[@class=’total’]/ancestor::tr | The table row that contains a total |
(//article)[1] | The first article in the whole document |
//tr[position() > 1] | Every row except the first in each table body |
XPath 1.0 also has a set of functions for strings, numbers and node sets: contains, starts-with, normalize-space, string-length, count, position and last are the ones most scrapers need. Expressions can be combined with “and”, “or” and the union operator, written as a vertical bar.
A worked example
Suppose an annual report page has a financial table with no IDs or useful classes. Each row has a label in the first cell and figures for three years in the next cells, and you need the most recent revenue figure.
With CSS selectors alone you would select every row, loop through them in code, and check the first cell’s text. With XPath it is one expression: “//tr[td[1][normalize-space()=’Revenue’]]/td[2]”. It reads as: find the row whose first cell, with whitespace trimmed, says Revenue, and return its second cell. If the table puts the label in a th element, change “td[1]” to “th” and the rest stays the same.
The result is a string such as “1,284.5”, which then needs data normalisation into a number, with a check against the column header to confirm the year and units. A similar approach works for definition lists, key-value blocks and forms, where the reliable anchor is the label text and the value sits next to it.
The same pattern makes the scraper resilient to a common kind of change. If the company adds a new row above Revenue, or reorders the rows, a position-based selector would return the wrong figure, while the label-anchored expression still finds the right row. If they add a fourth year column on the left, the column index changes, which is why reading the header row and mapping column names to positions is worth the extra few lines.
Where XPath is used
In browsers, document.evaluate runs an XPath expression against the page, and developer tools let you test expressions in the console. Headless browser libraries such as Playwright, Puppeteer and Selenium accept XPath locators, although their documentation tends to prefer CSS or role-based locators for maintainability.
Outside the browser, lxml in Python and similar libraries in other languages evaluate XPath against parsed HTML very quickly, and the Scrapy framework supports XPath and CSS side by side. These work on page source, so content added by scripts needs JavaScript rendering first. HTML parsing covers how parsers repair messy markup into a tree XPath can walk.
Test automation teams reach for XPath when an element has no stable ID or test attribute but sits next to something with fixed text, such as a heading, a label or a column title. It is also common in enterprise tools and RPA products, which often store element locators as XPath behind the scenes.
XPath is also the natural tool for XML itself: RSS and Atom feeds, configuration files, office document internals, data exchange formats and sitemap.xml files that list a site’s URLs. A web crawler that reads sitemaps often uses a short XPath expression to pull every loc element out of the file.
XPath vs CSS selectors
Both languages select nodes, and most scrapers use both. CSS selectors are shorter and familiar to front-end developers. XPath is more expressive.
Need | XPath | CSS selectors |
|---|---|---|
Select by tag, ID, class or attribute | Yes, longer syntax | Yes, shorter syntax |
Select by text content | Yes | No standard way |
Move to parent, ancestor or preceding sibling | Yes, through axes | Limited, through :has() |
Return attribute values or text nodes directly | Yes | No, read them in code |
Work on XML with namespaces | Yes | Poorly |
Readability for most web developers | Lower | Higher |
The practical rule is to start with CSS selectors and switch to XPath when an expression needs text matching, upward movement or direct access to attributes. Mixing the two in one scraper is common and causes no problems.
Writing XPath that lasts
Avoid absolute paths. An expression like “/html/body/div[2]/div[1]/section/div[3]/span” is what browser tools produce when you copy an XPath, and it breaks when any wrapper changes. Anchor on something meaningful instead: an ID, a data attribute, a heading or a label’s text.
Be careful with class matching. “@class=’price’” fails when an element has several classes, and “contains(@class, ‘price’)” also matches “price-old” and “unit-price”. The robust 1.0 idiom is “contains(concat(‘ ‘, normalize-space(@class), ‘ ‘), ‘ price ‘)”, which is long but exact.
Trim text before comparing. Visible text often carries line breaks and spaces from the markup, so compare against “normalize-space()” rather than “text()”.
Handle namespaces in XML. Sitemaps, feeds and many XML formats declare a default namespace, and an expression such as “//url/loc” returns nothing until the namespace is registered with a prefix or the expression uses “local-name()”. This is the most common reason an apparently correct XPath finds no nodes in a sitemap.
Validate what comes back. As with any selector, check counts and formats on every run, and alert when they change sharply. Quiet failures, where an expression matches a different element after a redesign, are worse than loud ones.
Finally, the usual rules on access still apply. Respect robots.txt and site terms, prefer an official API where one exists, as web scraping vs API explains, and see is web scraping legal for the main legal questions.
XPath and LLM pipelines
XPath fits well when you know a site’s structure and need the same fields from many pages. When you need content from many different sites, maintaining expressions per site becomes the bottleneck. Teams then switch to generic extraction: boilerplate removal to isolate the main content, HTML to Markdown to keep its structure, and structured data extraction with a model to fill a schema. Some pipelines combine the two, asking a model to propose XPath expressions for a new site, then running those expressions cheaply on every page and validating the results.
Where Exabase fits
Exabase does not evaluate custom XPath expressions. It covers the cases where you want a page’s content without writing per-site selectors.
Exabase Extract takes a URL, renders it with JavaScript and returns the title, site name and page content as text chunks; the same endpoint handles PDFs, images, audio and video. The extraction guide and the POST /v2/extract reference describe the request, and the website to JSON tool shows the output for one URL. The file extraction page explains how this replaces separate parsers per format.
Stored as Resources, extracted pages are indexed for Deep Search, which returns the passage that answers a question with its location, so an agent can find “the latest revenue figure” without an expression tied to one page’s layout. For comparing scraping services, the best web scraping API roundup and Exabase vs Firecrawl are good starting points.
Frequently asked questions
What is XPath used for?
XPath is used to select nodes in XML and HTML documents. In practice that means picking elements out of web pages for scraping and testing, and reading values from XML files such as feeds, sitemaps and configuration.
Is XPath better than CSS selectors?
XPath is more expressive, and CSS selectors are easier to read. Use CSS for simple selections and XPath when you need to match text, move up the tree or read attributes directly.
Which version of XPath do browsers support?
Browsers support XPath 1.0 through document.evaluate. Later versions are available in XML processing tools but not in browsers or most scraping libraries.
Why does my XPath return nothing on a sitemap or XML feed?
The file almost certainly declares a default namespace. Register the namespace with a prefix in your XPath library, or match elements with local-name() instead of their plain names.
How do I select an element by its text with XPath?
Use a predicate on the text, such as //button[normalize-space()=’Save’] for an exact match or //a[contains(., ‘Pricing’)] for a partial one.
Should I copy XPath from browser developer tools?
Use it as a starting point only. Copied paths are absolute and break easily, so shorten them to anchor on an ID, attribute or label.
Do I need XPath to extract web pages with Exabase?
No. Exabase Extract returns a page’s content as text chunks without any selectors, and you can still apply XPath to the original HTML in your own code if you need specific fields.
Related pages: CSS selectors, DOM, HTML parsing, Sitemap.xml, Web scraping, Browser automation, Structured data extraction, Best web scraping API, File extraction