Python lxml不支持xpath语法“ starts-with”?

时间:2019-05-16 03:23:43

标签: python xpath lxml

str = """<ROOT>
<ITEM>
   <REVENUE_YEAR>2554-02</REVENUE_YEAR>
   <REGION>Central</REGION>
</ITEM>
<ITEM>
  <REVENUE_YEAR>2552-02</REVENUE_YEAR>
  <REGION>Central</REGION>
</ITEM>
<ITEM>
  <REVENUE_YEAR>2552-03</REVENUE_YEAR>
  <REGION>Central</REGION>
</ITEM>
</ROOT>"""

xml = etree.fromstring(str)
xpath_str = ".//ITEM[starts-with(REVENUE_YEAR,'2554')]"
result = xml.find(xpath_str)
print(result)

嗨,上面的代码引发了SyntaxError:谓词无效,是否表示lxml不支持starts-with?还有其他方法可以通过带有lxml的xpath查找REVENUE_YEAR元素(2554-02)吗?谢谢!

1 个答案:

答案 0 :(得分:2)

它支持xpath,但您需要使用xpath:

str = """<ROOT>
<ITEM>
   <REVENUE_YEAR>2554-02</REVENUE_YEAR>
   <REGION>Central</REGION>
</ITEM>
<ITEM>
  <REVENUE_YEAR>2552-02</REVENUE_YEAR>
  <REGION>Central</REGION>
</ITEM>
<ITEM>
  <REVENUE_YEAR>2552-03</REVENUE_YEAR>
  <REGION>Central</REGION>
</ITEM>
</ROOT>"""

xml = etree.fromstring(str)
xpath_str = ".//ITEM[starts-with(REVENUE_YEAR,'2554')]"
result = xml.xpath(xpath_str)
print(result) # which is a list containing only one element