How to use lxml to find an element by text?

You are very close. Use text()= rather than @text (which indicates an attribute).

e = root.xpath('.//a[text()="TEXT A"]')

Or, if you know only that the text contains “TEXT A”,

e = root.xpath('.//a[contains(text(),"TEXT A")]')

Or, if you know only that text starts with “TEXT A”,

e = root.xpath('.//a[starts-with(text(),"TEXT A")]')

See the docs for more on the available string functions.


For example,

import lxml.html as LH

text=""'\
<html>
    <body>
        <a href="https://stackoverflow.com/1234.html">TEXT A</a>
        <a href="http://stackoverflow.com/3243.html">TEXT B</a>
        <a href="http://stackoverflow.com/7445.html">TEXT C</a>
    <body>
</html>'''

root = LH.fromstring(text)
e = root.xpath('.//a[text()="TEXT A"]')
print(e)

yields

[<Element a at 0xb746d2cc>]

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)