如何在XPath中使用AND选择具有某些属性的特定元素?

时间:2016-04-12 09:13:16

标签: python python-2.7 xpath lxml

如果元素名称是[x或y或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中做同样的事情吗?

1 个答案:

答案 0 :(得分:2)

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

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