有效的XPath表达式 [英] Valid XPath expression

查看:96
本文介绍了有效的XPath表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只有两个问题:

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

推荐答案

  1. 如果XPath无效,则会出现异常.
  2. 如果请求的节点不存在,您将得到一个空结果 设置.
  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.

例如:

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.

这篇关于有效的XPath表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆