有效的XPath表达式
只有两个问题:
- 我怎么检查一个变量里的字符串是否是有效的XPath表达式?
- 如果请求的资源不存在,我怎么返回一个自定义的错误信息?
1 个回答
6
- 如果你写的XPath不对,就会出现错误。
- 如果你请求的节点不存在,那么结果会是空的。
举个例子:
from lxml import etree
from StringIO import StringIO
tree = etree.parse(StringIO('<foo><bar></bar></foo>'))
try:
tree.xpath('\BAD XPATH')
print '1. Valid XPath'
except etree.XPathEvalError, e:
print '1. Invalid XPath: ', e
if not tree.xpath('/foo/xxx'):
print '2. Requested node does not exist.'
运行结果如下:
1. Invalid XPath: Invalid expression
2. Requested node does not exist.