如何在Python的lxml中使用正则表达式和XPath?

3

我想要做的是:

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.

我不太理解 ":test" 的意思。能否有人结合文档内容进行解释一下?
1个回答

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'

请参考 http://exslt.org/regexp/ 和 http://exslt.org/regexp/functions/test/index.html 了解更多信息。基本上,re:test 指定了测试函数所在的命名空间。 - user621819

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接