【问题标题】:How to select specific elements with certain attributes using AND in XPath?如何在 XPath 中使用 AND 选择具有某些属性的特定元素?
【发布时间】:2016-04-12 09:13:15
【问题描述】:

如果元素名称是 [x or y or z] 并且具有定义的属性,我想选择同一棵树中的所有元素。在 PHP 中运行的示例是:

xpath = "//*[name()='x' or name()='y' or name()='z'][descendant::w[@attrib][@attrib2='".$variable."']]";

所以我试图在 python 2.7 中编写它的等价物:

xpath = "[//*[//x or //y or //z][descendant::w[@attrib][@attrib2='".{0}."']]".format(variable)

但这对我不起作用。实际上我不知道为什么 php 代码使用 name() ?我可以并且应该在 python 中做同样的事情吗?

【问题讨论】:

  • @Epodax 我删除了 php 标签。

标签: python python-2.7 xpath lxml


【解决方案1】:

我宁愿使用self::foo,而不是name()='foo'。以下 XPath 应该等同于您的第一个 XPath:

xpath = '''//*[self::x or self::y or self::z]
              [descendant::w[@attrib and @attrib2='{0}']]
        '''.format(variable)

【讨论】:

    猜你喜欢
    • 2012-11-30
    • 2010-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2016-05-04
    • 1970-01-01
    • 2019-09-29
    相关资源
    最近更新 更多