Java 硒获取文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23804123/
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
Selenium getText
提问by Lpgfmk
I want to getText() using By.id or By.cssSelector.
我想使用 By.id 或 By.cssSelector 来 getText()。
I managed to solve my problem by doing getAttribute("value"), but I don't understand why getText() doesn't work like I expect it, and I might need it so all help is appreciated.
我设法通过执行 getAttribute("value") 解决了我的问题,但我不明白为什么 getText() 不能像我期望的那样工作,我可能需要它,因此感谢所有帮助。
Here is the java:
这是java:
WebDriverWait wait = new WebDriverWait(driver, 10);
Boolean elementIsPresent = wait.until(ExpectedConditions.textToBePresentInElementValue(By.cssSelector("#general_service_name"),"[reg] general_service_name")); // true
//WebElement general_service_name = driver.findElement(By.cssSelector("#general_service_name"));
WebElement general_service_name = driver.findElement(By.id("general_service_name"));
// Display check
Boolean isDisplayed;
if(general_service_name.isDisplayed()) isDisplayed = new Boolean(true); else isDisplayed = false; //true
String text_empty = general_service_name.getText(); //""
String text_with_value = driver.findElement(By.id("general_service_name")).getAttribute("value"); //"[reg] general_service_name"
And html:
和 html:
<input id="general_service_name" type="text" value="[reg] title" name="general_service_name" style="float:left;"/>
采纳答案by azraelAT
http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/WebElement.html#getText()
http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/WebElement.html#getText()
getText() delivers the innerText of a WebElement.
getText() 提供 WebElement 的innerText。
Your input field does not have any inner Text. The text is found inside your value-attribute, hence accessing it via getAttribute("value") is the correct way to do it.
您的输入字段没有任何内部文本。文本位于您的值属性中,因此通过 getAttribute("value") 访问它是正确的方法。
回答by Danstahr
Simple answer - it's designed this way. getText()
parses the content of the tag (i.e. its innerText), which is obviously empty for inputs.
简单的答案 - 它是这样设计的。getText()
解析标签的内容(即其innerText),对于输入显然是空的。
回答by Boyka Zhu
Java
ele.getAttribute("innerHTML");
爪哇
ele.getAttribute("innerHTML");
This could get the text already in the background and not displayed on the page yet.
这可以使文本已经在背景中并且尚未显示在页面上。
回答by SeekanDestroy
You may use this if you want to search for a given text on a WebElement. Passing it directly or through a String
如果要在 WebElement 上搜索给定文本,可以使用此选项。直接传递或通过字符串传递
String textoToSearch = "Text inside Webelement";
driver.findElement(By.id("someID).getText().contains("textToSearch");