只有两个问题:
- 如何检查分配给变量的字符串是否对应于有效的 XPath 表达式?
- 如果请求的资源不存在,我如何返回自定义的错误消息?
最佳答案
- 如果 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.
关于python - 有效的 XPath 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22889021/