为什么我的XPath不能根据标签文本选择链接/按钮? [英] Why won't my XPath select link/button based on its label text?

查看:302
本文介绍了为什么我的XPath不能根据标签文本选择链接/按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 < a href =javascript:void(0)title =home> 
< span class =menu_icon>也许这里有更多文字< / span>
主页
< / a>

因此,对于上面的代码,当我写 // a 作为XPath,它被突出显示,但是当我编写 // a [contains(text(),'Home')] 时,它没有被突出显示。我认为这很简单,应该已经奏效了。



我的错误在哪里?

解决方案

$ b


  1. 是的,您可以在 @title ,但这不是OP的
    XPath失败的原因。

  2. 是的,XML和XPath区分大小写,所以 Home
    home 不一样,但是有一个<$ c作为 a 子元素的$ c> Home 文本节点,因此OP为
    ,正确使用 Home ,如果他不信任 @title 即可。






真正的问题



OP的XPath,

 // a [contains(text(),'Home')] 

表示选择其第一个文本节点包含子字符串 Home 的所有 a 元素。然而,第一个文本节点只包含空格。



说明: text()选择上下文节点的所有子文本节点, a 。当 contains()被赋予多个节点作为它的第一个参数时,它将接收 第一个 节点的字符串值,但是 Home 出现在第二个文本节点中,而不是第一个。



相反,OP应该使用这个XPath, / b>

  // a [text()[contains(。,'Home')]] 

这就是说用 选择所有 a



如果没有包围它空格,这个XPath可以用来测试是否相等而不是子字符串遏制:

  // a [text()[。=或者,使用周围的空格,可以使用这个XPath修剪掉它:[b]   

  // a [text()[normalize-space()='Home']] 






另见:




<a href="javascript:void(0)" title="home">
    <span class="menu_icon">Maybe more text here</span>
    Home
</a>

So for above code when I write //a as XPath, it gets highlighted, but when I write //a[contains(text(), 'Home')], it is not getting highlighted. I think this is simple and should have worked.

Where's my mistake?

解决方案

Other answers have missed the actual problem here:

  1. Yes, you could match on @title instead, but that's not why OP's XPath is failing where it may have worked previously.
  2. Yes, XML and XPath are case sensitive, so Home is not the same as home, but there is a Home text node as a child of a, so OP is right to use Home if he doesn't trust @title to be present.


Real Problem

OP's XPath,

//a[contains(text(), 'Home')]

says to select all a elements whose first text node contains the substring Home. Yet, the first text node contains nothing but whitespace.

Explanation: text() selects all child text nodes of the context node, a. When contains() is given multiple nodes as its first argument, it takes the string value of the first node, but Home appears in the second text node, not the first.

Instead, OP should use this XPath,

//a[text()[contains(., 'Home')]]

which says to select all a elements with any text child whose string value contains the substring Home.

If there weren't surrounding whitespace, this XPath could be used to test for equality rather than substring containment:

//a[text()[.='Home']]

Or, with surrounding whitespace, this XPath could be used to trim it away:

//a[text()[normalize-space()= 'Home']]


See also:

这篇关于为什么我的XPath不能根据标签文本选择链接/按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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