【问题标题】:how to get Text inside the Div and button tag如何在 Div 和按钮标签中获取文本
【发布时间】:2017-10-09 15:55:22
【问题描述】:
<div class="content-wrapper" style="min-height: 611px;">
  <div class="alert alert-success alert-dismissable">
    <button class="close" type="button" data-dismiss="alert" aria-hidden="true">×</button>
    The new customer role has been added successfully.
</div>

如何在 Button 标记之后获取此 Text。我尝试了很多方法,但我无法得到它。

//div[@class='alert alert-success alert-dismissable']

【问题讨论】:

  • 你能分享你的网址吗
  • 请澄清您的问题并包括您尝试过的内容。

标签: javascript java selenium xpath selenium-webdriver


【解决方案1】:

您可以使用//div[@class='alert alert-success alert-dismissable']/text() xpath 来定位文本The new customer role has been added successfully. 但是selenium 不支持xpath 中的text() 方法来定位文本节点。

尝试下面的代码从&lt;button&gt;标签中获取文本。

String button = driver.findElement(By.xpath("//button[@class='close'][@type='button']")).getText();       
System.out.println(button);

尝试下面的代码获取文本The new customer role has been added successfully.

JavascriptExecutor js = (JavascriptExecutor)driver;
Object str = js.executeScript("var value = document.evaluate(\"//button[@class='close']/following::node()[contains(., 'The new customer role has been added successfully.')]\",document, null, XPathResult.STRING_TYPE, null); return value.stringValue;");      
System.out.println(str.toString());

您可以详细探索from here

参考下图。

【讨论】:

  • 它返回 'x' 但他想要按钮后的文本
  • @iamsankalp89 你尝试过第二个 xpath 吗?尝试一次,然后更新我。
  • 好的,我会试着告诉你
  • 不,@janish 它也打印 X
  • 等一下,我会附上图片,看看它是否清楚地显示了正确的结果..有关更多详细信息,请参阅上面的图片。
【解决方案2】:

我不确定您的 HTML,但您可以尝试使用此 XPath

//*[@class='alert alert-success alert-dismissable']

使用 java getText() 将从 html 中获取您的文本

driver.findElement(By.xpath(" //*[@class='alert alert-success alert-dismissable']")).getText();

让我知道 XPath 是否有效

【讨论】:

  • 这似乎不是正确的答案。因为当您以String a = driver.findElement(By.xpath("//*[@class='alert alert-success alert-dismissable']")).getText(); System.out.println(a); 执行上述答案时,它会给您Button tag textafter the button tag text. 这两个文本,但@Raghavendra K 只需要按钮标签之后的文本。
【解决方案3】:

我想你已经尝试过使用下面的 xpath

//*[@class='alert alert-success alert-dismissable']

您能否检查一下警告框(我假设它是来自给定 html 的警告框)是否作为新窗口弹出。在这种情况下,您需要切换到新窗口。

还要检查是否有alert弹窗的overlay属性

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 2012-03-02
    • 1970-01-01
    • 2015-11-25
    • 1970-01-01
    • 1970-01-01
    • 2015-07-17
    相关资源
    最近更新 更多