Valid XPath expression

假装没事ソ 提交于 2019-12-21 05:07:13

问题


Just two questions:

  1. How can I check if the string assigned to a variable corresponds to a valid XPath expression?
  2. How can I return a customized error message in case the requested resource does not exist?

回答1:


  1. If the XPath is invalid, you'll get an exception.
  2. If the requested node does not exist, you'll get an empty result set.

For example:

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

Runs as follows:

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


来源:https://stackoverflow.com/questions/22889021/valid-xpath-expression

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!