Java 如何在 Selenium Webdriver 中获取元素的文本()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22087952/
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 gettext() of an element in Selenium Webdriver
提问by Santhosh S
I am finding a textbox by its ID. I need to get the content which is already there inside the text box. For that I am using gettext()method but it is returning the ID value
我正在通过其 ID 找到一个文本框。我需要获取文本框中已经存在的内容。为此,我正在使用gettext()方法,但它正在返回 ID 值
Content in text box is: Santhosh
文本框中的内容是:Santhosh
The output I am getting is = [[FirefoxDriver: firefox on XP (c0079327-7063-4908-b20a-a606b95830cb)] -> id: ctl00_ContentPlaceHolder1_txtName]
我得到的输出是 = [[FirefoxDriver: firefox on XP (c0079327-7063-4908-b20a-a606b95830cb)] -> id: ctl00_ContentPlaceHolder1_txtName]
The code is below
代码如下
CODE:
代码:
WebElement TxtBoxContent = driver.findElement(By.id(WebelementID));
TxtBoxContent.getText();
System.out.println("Printing "+TxtBoxContent);
RESULT:
结果:
Printing [[FirefoxDriver: firefox on XP (c0079327-7063-4908-b20a-a606b95830cb)] -> id: ctl00_ContentPlaceHolder1_txtName]
采纳答案by Richard
You need to print the result of the getText(), you're currently printing the object TxtBoxContent.
您需要打印 的结果getText(),您当前正在打印对象TxtBoxContent。
getText()will only get the inner text of an element. To get the value, you need to use getAttribute().
getText()只会获取元素的内部文本。要获取该值,您需要使用getAttribute().
WebElement TxtBoxContent = driver.findElement(By.id(WebelementID));
System.out.println("Printing " + TxtBoxContent.getAttribute("value"));
回答by Dipti Bhushetty
text = driver.findElement(By.id('p_id')).getAttribute("innerHTML");
回答by Sags
You need to store it in Stringvariable first before displaying like so:
String在显示之前,您需要先将其存储在变量中:
String Txt = TxtBoxContent.getText();
System.out.println(Txt);

