【问题标题】:Selenium: find element by visible TextSelenium:通过可见文本查找元素
【发布时间】:2016-05-24 20:37:17
【问题描述】:

在 html 页面中,我有以下应答器:

<button class="....." data-toggle="dropdown">
Text: Title of the button                        
<span class="....."/>
</button>

我想通过可见文本检测这个按钮 Text: Title of the button 问题是我正在尝试使用以下 Xpath 检测它

.//*[contains(text(),"Text: Title of the button")]

但它不起作用。 我怎样才能检测到这个按钮?

仅供参考:我无法使用 class 检测到它,因为与此类匹配的节点不止一个。

【问题讨论】:

  • 试试 //*[contains(text(),"Text: Title of the button")][0] 或分享代码。
  • 请查看该文本是否出现在按钮标签内。如果是,请检查文本的部分 //button[contains(text(),'Part of Title of the button')]
  • @IAH2iV 可以看到上面HTML的代码,这个Text是在button标签里面,但是问题是button里面包含了另一个balise。
  • @Kichan Patel,问题不在于 XPATH 有更多匹配节点,而是 XPATH 与任何节点都不匹配。

标签: html selenium xpath


【解决方案1】:

contains(text(), '...') 仅评估当前上下文元素中的第一个文本节点子节点。对于您发布的示例元素,这应该没有任何问题(请参阅demo,但它不适用于以下元素,因为button 中的第一个文本节点是位于span 之前的换行符:

<button class="....." data-toggle="dropdown">
<span class="....."/>
Text: Title of the button                        
</button>

要评估当前上下文元素的所有文本节点子节点,请改用以下形式:

.//*[text()[contains(.,"Text: Title of the button")]]

demo

上面的 XPath 测试单个文本节点是否包含某些文本。

【讨论】:

    【解决方案2】:

    您好,请按照以下方式进行操作

    By.xpath("//button[contains(text(),'Text: Title of the button')]")
    please put Text: Title of the button in single quote.
    Also if more html source code is provided then i can come up with a better locator stratgey
    

    你也可以基于类名或通过talking属性来做到这一点 xpath 中的 data-toggle="dropdown" 以及 //*[@data-toggle='dropdown']

    //获取列表中按钮的类名

    List<WebElement> buttons= driver.findElements(By.className("className"));
    Now you can select your concerned button on the basis of index (in java index starts 
    form zero)
    

    【讨论】:

    • 事实上我的问题是 - 还有其他方法可以通过内部文本检测元素,除了 Contains(text()," ") 因为在我的情况下所有其他解决方案都不是更好的方法。有超过 12 个带有 Class 的匹配节点和超过 10 个带有数据切换的匹配节点,我有超过 5 个按钮,我想用基于可见文本的通用解决方案来检测它们。
    • ok plz Confirm By.xpath("//button[contains(text(),'Text: Title of the button')]") 这行是否有效
    • 不,这条线不起作用,我以前试过!。我有没有应答器的示例在元素内部,只有文本和它可以工作,但在我的 CAS 号中。
    • 能否贴出你问题领域的完整源代码
    • 对不起,源代码是机密的,我不能发布它。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 2017-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-12
    • 2017-08-08
    相关资源
    最近更新 更多