有效的XPath表达式

bul*_*che 5 python xml xpath lxml

只有两个问题:

  1. 如何检查分配给变量的字符串是否对应于有效的XPath表达式?
  2. 如果请求的资源不存在,如何返回自定义错误消息?

kjh*_*hes 5

  1. 如果XPath无效,您将获得异常.
  2. 如果请求的节点不存在,您将获得一个空的结果集.

例如:

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.'
Run Code Online (Sandbox Code Playgroud)

运行如下:

1. Invalid XPath:  Invalid expression
2. Requested node does not exist.
Run Code Online (Sandbox Code Playgroud)