如何使用python验证给定的xpath。在下面的代码中,我正在基于给定的xpath获取值。在此之前,我需要验证xpath是否有效。
def getElementsData(xpath):
elements = list()
for elem in root.findall(xpath):
elements.append(elem.text)
return elements
预先感谢
答案 0 :(得分:1)
使用出色的lxml
library,它可以使用xpath:
d = lxml.etree.fromstring(your_xml) # if html use lxml.html.fromstring
try:
result = d.xpath(some_xpath_expression)
except lxml.etree.XPathEvalError:
print('The expression is invalid')
if not result:
print('Expression is valid but no results')
else:
print('Expression valid! {} results found'.format(len(result)))
答案 1 :(得分:0)
我找到了我们可以实现的答案
def validate(xpath):
if root.findall(xpath):
print("valid")
else:
print("not valid")