Web scraping
How do I select elements by their text with XPath?
Write a predicate on the text: //button[text()="Next"] for an exact match, or //a[contains(., "Next")] when the text is longer or split across child tags.
The direct answer
In XPath you filter elements with a predicate in square brackets, and text is just another value to test. //h2[text()="Shipping"] matches an h2 whose own text node is exactly "Shipping". //h2[contains(., "Shipping")] matches when the full text, including nested tags, contains the word. Add normalize-space() to ignore stray spaces and line breaks, which real pages are full of.
text() versus the dot
This difference causes most failed text queries. text() refers to the text nodes directly inside the element. The dot . means the element's whole string value, which joins text from all descendants. For the markup <a><span>Download</span> report</a>:
| Expression | Matches? | Why |
|---|---|---|
//a[text()="Download report"] | No | the link's own text node is only " report" |
//a[contains(text(), "Download")] | No | "Download" sits inside the span |
//a[contains(., "Download")] | Yes | the string value is "Download report" |
//a[normalize-space()="Download report"] | Yes | full text with spaces tidied |
As a habit, use . or normalize-space() unless you know the text is a single direct node.
Case-insensitive matching
XPath 1.0, which browsers and lxml implement, has no lower-case function. The standard workaround is translate():
//button[contains(translate(., "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz"), "accept")]
It is verbose but works everywhere. For anything fancier, select a wider set and filter in your own language.
Using it from code
# Python with lxml
import lxml.html as lxh
doc = lxh.fromstring(raw_markup)
next_href = doc.xpath('//a[normalize-space()="Next page"]/@href')
# Selenium ("xpath" is the value behind By.XPATH)
driver.find_element("xpath", '//button[contains(., "Accept all")]').click()
In Playwright, prefix the expression with xpath=, although its own get_by_text() is usually simpler. Puppeteer accepts XPath through the ::-p-xpath() selector in recent versions.
Matching text, then moving elsewhere
Text is often the only stable anchor on a page, while the value you want sits next to it. Find the label by text and step from there with an axis, for example to the parent row or a following cell. The companion question on selecting sibling elements covers those axes.
Pitfalls
- Non-breaking spaces.
is not a normal space, andnormalize-space()does not remove it. If an exact match fails on text that looks right, trycontains()on a shorter part. - Translated sites. Text selectors break when the page language changes. Pin the language with a URL or an
Accept-Languageheader. - Too broad a match.
//*[contains(., "Price")]matches html, body and every ancestor too. Name the element type. - Quotes inside the text. If the text contains a double quote, wrap the literal in single quotes, or use
concat()when it contains both.
Where this matters for CAPTCHA pages
Text matching is a handy way to detect a block in a script: an element containing "verify you are human" or a frame titled "reCAPTCHA" tells you to stop parsing and solve first. From there, read the site key and send a task as described in the API docs.
Text anchors versus attribute anchors
Text is readable and often stable, but it is not always the best anchor. If the element has a meaningful id, name or data-testid, match that instead, because developers change wording far more often than they rename test hooks. Text anchors shine where markup is generic: a table full of plain td cells, a footer of identical links, or a menu built from unlabeled div elements. A good rule is to combine both when you can, for example //section[@id="specs"]//th[normalize-space()="Weight"], so the text only has to be unique inside one known block.
Keep text expressions in one place in your code, such as a small dictionary of labels, rather than scattered through functions. When the site rewords a button, you change one line. If you scrape the same layout in several languages, that dictionary can hold one entry per language, and the rest of the XPath stays the same.
Common questions
Is contains() case sensitive?
Yes. Use translate() to lower-case the text first, or filter results in your own code.
Can XPath match text with a regular expression?
Not in XPath 1.0, which browsers and lxml use. lxml offers EXSLT regex functions as an extension.
Why does text()= fail when the words look identical?
There may be extra whitespace, a non-breaking space, or the words may be split across child elements.
Does CSS have an equivalent?
Not in the standard. Some tools add their own text pseudo selectors, but XPath works across all of them.
How do I get the text instead of the element?
End the path with /text() or wrap it with string(), for example string(//h1).
Keep reading
- XPathXPath navigates a document tree in any direction, matches on text, and handles cases where CSS selectors run out of road.
- How do I select sibling elements in XPath?The following-sibling and preceding-sibling axes walk sideways from an anchor, ideal for label and value pairs in tables and lists.
- Can XPath be used in Beautiful Soup?Beautiful Soup has no XPath engine; use its CSS select method, or parse the same HTML with lxml when you need XPath.
- HTML parsingHTML parsing turns markup into a tree your code can query, and tolerant parsers rebuild broken pages the same way browsers do.