如何使用 Java 在 WebDriver 中获取按钮的标题/文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13006311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get caption/text of button in WebDriver using Java
提问by Ripon Al Wasim
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?
但不幸的是,没有检索到任何文本。发现空白/空文本。有谁能够帮我?
回答by Pani Kumar
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");
driver.findElement(By.XPath("//input[@name='submit']")).getAttribute("value");
回答by some_other_guy
This should work -
这应该有效 -
String actualButtonCaption = driver.findElement(By.name("Submit")).getAttribute("value");
回答by Zohaib
try associating an ID
with input and then find element by 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.
尝试将 anID
与输入相关联,然后按 ID 查找元素。如果出现文本,则xpath有问题,您可以使用Firefox的插件分析确切的运行时间xpath。
回答by Ripon Al Wasim
I have got the solution by using JavaScript. The code is as below:
我通过使用 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);
It works fine. The caption of button is printed as "Save"
它工作正常。按钮的标题打印为“保存”