簡體   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