如何使用Java在WebDriver中获取字幕/按钮文本



我有以下"保存"按钮的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);

它可以正常工作。按钮的标题被打印为"保存"

最新更新