我正在尝试:
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("aBaBc ") >>> 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 = 'link1' >>> tree = fromstring(data) >>> tree.xpath('//a[re:test(@id, "^hypProduct_[0-9]+$")]', namespaces={'re': "http://exslt.org/regular-expressions"})[0].attrib["id"] 'hypProduct_10'