How to select elements by text in XPath
Choose the right XPath text test for the job: exact equality when the wording is stable, contains() when only a fragment is reliable, and helpers for whitespace, case, nested markup, and attribute values.
The examples below use Python with lxml and Selenium, and the protected modules listed with each section carry the exact expressions to copy.
Exact versus partial matching
Start by deciding how much of the label you can trust. If the full wording is fixed, equality is the tightest test: module code0001 shows the pattern, and a single extra space or a capitalisation change will make it miss. When the label is longer or partly dynamic, a substring test is safer: module code0002. A practical rule is to use equality for controlled copy and contains() for longer, changing, or only partly known text. In the worked Python and Selenium examples (modules code0003 and code0004), an exact search for a short word returns nothing against a longer sentence, while the partial search finds it.
contains(), starts-with() and normalize-space()
Three helpers cover most real-world variation. contains() finds a fragment anywhere in the text, as in module code0005. starts-with() anchors the match to the beginning, as in module code0006, so a greeting at the start matches but the same words later in a sentence do not. normalize-space() trims and collapses ordinary whitespace before comparison, as in module code0007, which helps when markup adds padding around a word. Module code0008 demonstrates all three in Python. Use these only where needed, because each function adds cost when applied across a large document.
Case-insensitive matching with translate()
XPath comparisons are case sensitive, so Submit, submit and SUBMIT are different values. XPath 1.0, used by tools such as lxml via libxml2, has no lower() or upper() function. The workaround in module code0009 converts both the element text and the target to lowercase with translate() before comparing. Module code0010 gives the general translate() form: each character in the source is replaced by the character in the same position of the replacement string, characters with no replacement are removed, and others stay unchanged. Module code0011 illustrates the mapping on a short string, and module code0012 shows the result in Python, where one exact match becomes three case-insensitive matches.
Quotes, entities and special characters
Real pages contain apostrophes, quotation marks, decoded entities, non-breaking spaces, and Unicode symbols. If the text contains a single quote, wrap the literal in double quotes (module code0013); if it contains a double quote, use single quotes (module code0014); if it contains both, assemble the literal with concat() (module code0015). After HTML parsing, entities are decoded, so match the decoded characters rather than the entity spelling. normalize-space() does not remove non-breaking spaces, so translate a non-breaking space to a normal space first, as in module code0016. Unicode and emoji can be matched directly in a UTF-8 Python file, as in module code0017. Module code0018 combines quotes, entities and non-breaking-space handling in one Python example.
Matching attribute text instead of inner text
When the wording lives in an attribute such as alt, title, aria-label or data-*, replace text() with @attribute and reuse the same tests. Modules code0019 and code0020 contrast inner-text and attribute forms. Exact, partial, prefix, whitespace-trimmed and case-insensitive attribute patterns appear in modules code0021 to code0025, and module code0026 applies them to a button, an image and a link. Prefer an attribute hook when one exists, because it is usually more stable than visible copy.
Performance and stability checklist
A short checklist keeps selectors fast and less brittle: narrow the search from a known parent or tag instead of scanning the whole document; in Selenium, locate a container first and then use a relative search inside it. Prefer stable attributes such as id, data-test or aria-* over text, and prefer equality over contains() when the value is controlled. Combine selective predicates, limit expensive functions such as translate(), contains() and normalize-space() to a smaller subtree, and add a tag hint when the element type is known. Compile a repeatedly used lxml selector once and reuse it, wait for the right state before querying dynamic content, test in browser devtools first, and use positional indexes sparingly because they break when the document changes.
Common errors and debugging
Most failures come from a small set of mismatches. Extra spaces or newlines defeat a plain equality test, so wrap the text with normalize-space(). Hidden or not-yet-visible elements can be present in the DOM, so wait for visibility in Selenium. text() sees only one direct text node, so markup such as a button containing a nested span returns only the first fragment; use normalize-space(.) or string(.) to include nested text. Remember that XPath indexes start at 1, that entities are decoded before matching, and that @attr and text() are easy to confuse. To debug, test the expression in browser devtools, print the matched elements, build the predicate step by step from a simple tag search, and check whether JavaScript-loaded text is invisible to a plain request-based parser.
| Goal | Test to use | When it fits |
|---|---|---|
| Exact inner text | text() = "..." | Full wording is known and stable |
| Partial inner text | contains(text(), "...") | Only a fragment is reliable |
| Text begins with a string | starts-with(text(), "...") | Prefix is stable, remainder varies |
| Ignore surrounding spaces | normalize-space(text()) = "..." | Markup adds padding or newlines |
| Ignore case | translate() on both sides | XPath 1.0 without lower() |
| Attribute value | @attr with =, contains() or starts-with() | Wording is in alt, title, aria-label or data-* |
| All nested text | . or string(.) | Text is split across nested tags |
Case-sensitive unless translate() is added; normalize-space() handles ordinary whitespace but not non-breaking spaces.
Frequently asked questions
How do I select an element by exact text in XPath?
Use text() = "..." for an exact, case-sensitive match; whitespace must match exactly.
How do I select an element by partial text in XPath?
Use contains(text(), "...") to match a substring; it is case-sensitive.
How can I ignore leading or trailing spaces in XPath text?
Use normalize-space(); for example //button[normalize-space(text()) = "Submit"] trims and collapses spaces.
Can I do case-insensitive text matching in XPath?
XPath 1.0 has no lower() or upper(); simulate with translate() on both sides, then compare.
How do I select elements with text or another condition?
Combine predicates with or (or and) inside []; for example //button[text() = "Submit" or @id = "submit-btn"].
How do I find elements by text inside attributes instead of the element's content?
Target attributes with @attr and use =, contains(), or starts-with(); for example //img[@alt = "Logo"] or //button[contains(@aria-label, "Submit")].
Can I select elements with text containing special characters like quotes?
Wrap the string in the opposite quote type; if it contains both single and double quotes, build it with concat().
How do I get all text nodes within an element using XPath?
text() grabs direct text children only; use string(.) or normalize-space(.) for the full string including nested nodes.
How do I select elements whose text starts or ends with a specific string?
Use starts-with(text(), "..."); emulate ends-with in XPath 1.0 via substring() plus string-length().
What's the difference between text() and . in XPath?
text() selects direct text-node children; . (or string(.)) is the element's full string value including descendants.