有效的XPath表达式

6 投票
1 回答
1467 浏览
提问于 2025-04-18 01:31

只有两个问题:

  1. 我怎么检查一个变量里的字符串是否是有效的XPath表达式?
  2. 如果请求的资源不存在,我怎么返回一个自定义的错误信息?

1 个回答

6
  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.'

运行结果如下:

1. Invalid XPath:  Invalid expression
2. Requested node does not exist.

撰写回答