繁体   English   中英

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

[英]How do i use regular expressions in python lxml, 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.

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

在您的情况下,表达式将是:

//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'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM