Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use regular expression in lxml xpath?

I'm using construction like this:

doc = parse(url).getroot()
links = doc.xpath("//a[text()='some text']")

But I need to select all links which have text beginning with "some text", so I'm wondering is there any way to use regexp here? Didn't find anything in lxml documentation

like image 782
Arty Avatar asked Sep 10 '25 17:09

Arty


2 Answers

You can do this (although you don't need regular expressions for the example). Lxml supports regular expressions from the EXSLT extension functions. (see the lxml docs for the XPath class, but it also works for the xpath() method)

doc.xpath("//a[re:match(text(), 'some text')]", 
        namespaces={"re": "http://exslt.org/regular-expressions"})

Note that you need to give the namespace mapping, so that it knows what the "re" prefix in the xpath expression stands for.

like image 161
Steven Avatar answered Sep 12 '25 11:09

Steven


You can use the starts-with() function:

doc.xpath("//a[starts-with(text(),'some text')]")
like image 26
John Kugelman Avatar answered Sep 12 '25 11:09

John Kugelman