如何为特定节点编写条件xpath选择?

时间:2017-04-18 22:17:43

标签: javascript xml xslt xpath ecma

所以我在chrome,autopagerizer上添加了一个用户脚本。

目前我正在使用

//div[@class=\'entry-content\']/p[contains(.,\'chapter\') or contains(.,\'Chapter\') or preceding-sibling::p[contains(.,\'Chapter\')] and (following-sibling::p[contains(.,\'Translator Ramblings\')] or following-sibling::p[contains(.,\'Translating Ramblings\')] or following-sibling::p[contains(.,\'Ramblings\')] or following-sibling::p[starts-with(.,\'Translator\')] or following-sibling::p[starts-with(.,\'Translating\')])] 

我想要一个条件参数,当上面的代码没有解析任何东西时,它会选择

//h3[contains(.,\'Share this\')]

相反。我只希望在这种情况下选择h3。我无法弄清楚如何在xpath中编写这个,我查找了其他相关问题但他们没有解决这个问题。如果我用xpath无法解决这个问题,我将如何使用javascript解决这个问题?我在铬上使用油脂猴子。

1 个答案:

答案 0 :(得分:1)

基本上,使用纯XPath 1.0实现所解释的模式可以如下:

expression1 | expression2[not(expression1)]

所以,在你的问题的背景下:

  • expression1(截断)://div[@class=\'entry-content\']/p[...]
  • 表达式2://h3[contains(.,\'Share this\')]
  • 溶液:

    //div[@class=\'entry-content\']/p[...]  | 
      //h3[contains(.,\'Share this\')]
          [not(//div[@class=\'entry-content\']/p[...])]
    

如果在Javascript的帮助下实现,这可能会更加清晰。只需执行expression1,如果结果长度为0,则执行expression2。

相关问题