[英]How to get caption/text of button in WebDriver using Java
I have the following HTML code for "Save" button: 我的“保存”按钮具有以下HTML代码:
<input type="submit" onclick="return confirm('Sure to change global settings?')" value="Save" name="submit">
I want to retrieve the caption of button. 我想检索按钮的标题。 I used the following code to do that:
我使用以下代码来做到这一点:
String actualButtonCaption = driver.findElement(By.xpath("//input[@value='Save']")).getText();
I also used the absolute xpath as below: 我还使用了绝对的xpath,如下所示:
String actualButtonCaption = driver.findElement(By.xpath("//html/body/form/div[3]/div[2]/input")).getText();
But unfortunately, no text was retrieved. 但是很遗憾,没有找到任何文本。 Blank/empty text was found.
找到空白/空文本。 Can anybody help me?
有谁能够帮助我?
getAttribute
method could be used to retrieve the attribute values. getAttribute
方法可用于检索属性值。
In this case following would return the caption: 在这种情况下,以下将返回标题:
driver.findElement(By.XPath("//input[@name='submit']")).getAttribute("value");
try associating an ID
with input and then find element by ID. 尝试将
ID
与输入相关联,然后按ID查找元素。 If text comes out, then there is a problem with xpath, you can analyze the exact run time xpath by using plugin of Firefox. 如果出现文本,则说明xpath存在问题,您可以使用Firefox插件分析确切的运行时xpath。
这应该工作-
String actualButtonCaption = driver.findElement(By.name("Submit")).getAttribute("value");
I have got the solution by using JavaScript. 我已经通过使用JavaScript获得了解决方案。 The code is as below:
代码如下:
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);
It works fine. 工作正常。 The caption of button is printed as "Save"
按钮的标题打印为“保存”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.