Java 如何使用硒获取 WebElement 文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37298400/
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 WebElement text with selenium
提问by david hol
Please see the following element:
请参阅以下元素:
<div class="success"><button class="close" data-dismiss="alert" type="button">×</button>
User 'MyUser' deleted successfully</div>
Find my element:
找到我的元素:
driver.findElement(By.cssSelector("div.success")
So after found this div
and get the text using selenium with getText
or getAttribute("innerHTML")
the return:
所以在找到这个div
并使用 selenium withgetText
或getAttribute("innerHTML")
return获取文本后:
×
User 'MyUser' deleted successfully
So my question is how to get only the last line without this x
所以我的问题是如何在没有这个的情况下只获得最后一行 x
采纳答案by Florent B.
The text you want is present in a text node and cannot be retrieved directly with Selenium since it only supports element nodes.
您想要的文本存在于文本节点中,无法直接使用 Selenium 检索,因为它仅支持元素节点。
You could remove the beginning :
您可以删除开头:
String buttonText = driver.findElement(By.cssSelector("div.success > button")).getText();
String fullText = driver.findElement(By.cssSelector("div.success")).getText();
String text = fullText.substring(buttonText.length());
You could also extract the desired content from the innerHTML
with a regular expression:
您还可以innerHTML
使用正则表达式从 中提取所需的内容:
String innerText = driver.findElement(By.cssSelector("div.success")).getAttribute("innerHTML");
String text = innerText.replaceFirst(".+?</button>([^>]+).*", "").trim();
Or with a piece of JavaScript:
或者使用一段 JavaScript:
String text = (String)((JavascriptExecutor)driver).executeScript(
"return document.querySelector('div.success > button').nextSibling.textContent;");
回答by Naman
WebElement element = driver.findElement(By.className("div.success")
element.getText();
shall help you get the text of the div
将帮助您获取 div 的文本