繁体   English   中英

如何使用Java在WebDriver中获取按钮的标题/文本

[英]How to get caption/text of button in WebDriver using Java

我的“保存”按钮具有以下HTML代码:

<input type="submit" onclick="return confirm('Sure to change global settings?')" value="Save" name="submit">

我想检索按钮的标题。 我使用以下代码来做到这一点:

String actualButtonCaption = driver.findElement(By.xpath("//input[@value='Save']")).getText();

我还使用了绝对的xpath,如下所示:

String actualButtonCaption = driver.findElement(By.xpath("//html/body/form/div[3]/div[2]/input")).getText();

但是很遗憾,没有找到任何文本。 找到空白/空文本。 有谁能够帮助我?

getAttribute方法可用于检索属性值。

在这种情况下,以下将返回标题:

driver.findElement(By.XPath("//input[@name='submit']")).getAttribute("value");

尝试将ID与输入相关联,然后按ID查找元素。 如果出现文本,则说明xpath存在问题,您可以使用Firefox插件分析确切的运行时xpath。

这应该工作-

String actualButtonCaption = driver.findElement(By.name("Submit")).getAttribute("value");

我已经通过使用JavaScript获得了解决方案。 代码如下:

WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor) driver;
String ss = (String)jse.executeScript("var x=document.getElementsByName('submit')[0].value; return x");
System.out.println("Caption of Save button: " + ss);

工作正常。 按钮的标题打印为“保存”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM