我如何在python lxml,XPath中使用正则表达式

时间:2015-12-29 05:29:45

标签: python regex xpath

我正在尝试:

for element in root.xpath('//a[@id="hypProduct_[0-9]+"]'):

如何在xpath元素选择器(lxml)中使用[0-9] +? 文档声明:

By default, XPath supports regular expressions in the EXSLT namespace:

>>> regexpNS = "http://exslt.org/regular-expressions"
>>> find = etree.XPath("//*[re:test(., '^abc$', 'i')]",
...                    namespaces={'re':regexpNS})

>>> root = etree.XML("<root><a>aB</a><b>aBc</b></root>")
>>> print(find(root)[0].text)
aBc

You can disable this with the boolean keyword argument regexp which defaults to True.

我没有遵循:测试的东西。有人可以在文档的上下文中解释这一点。

1 个答案:

答案 0 :(得分:6)

在您的情况下,表达式为:

//a[re:test(@id, "^hypProduct_[0-9]+$")]

演示:

>>> from lxml.html import fromstring
>>> 
>>> data = '<a id="hypProduct_10">link1</a>'
>>> tree = fromstring(data)
>>> tree.xpath('//a[re:test(@id, "^hypProduct_[0-9]+$")]', namespaces={'re': "http://exslt.org/regular-expressions"})[0].attrib["id"]
'hypProduct_10'