如何使用selenium获取WebElement文本 [英] How to get WebElement text with selenium
问题描述
请参阅以下内容:
< div class =success>< button class =close data-dismiss =alerttype =button>×< / button>
用户'MyUser'已成功删除< / div>
找到我的元素:
driver.findElement(By.cssSelector(div.success)
所以在找到这个 div
后,使用selenium和 getText
或获取文本getAttribute(innerHTML )
返回:
×
用户'MyUser'已成功删除
所以我的问题是如何只获得没有这个 x $ c的最后一行$ c>
您想要的文本存在于文本节点中,无法直接使用Selenium检索,因为它只支持元素你可以删除开头:
String buttonText = driver.findElement(By.cssSelector(div.success> button))。getText();
String fullText = driver.findElement(By.cssSelector(div.success) ))。getText();
String text = fullText.subs特林(buttonText.length());
您还可以从 innerHTML $ c $中提取所需内容c>使用正则表达式:
String innerText = driver.findElement(By.cssSelector( div.success ))的getAttribute( innerHTML的);
String text = innerText.replaceFirst(。+?< / button>([^>] +)。*,$ 1)。trim();
或使用一段JavaScript:
String text =(String)((JavascriptExecutor)driver).executeScript(
return document.querySelector('div.success> button') ).nextSibling.textContent;);
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:
×
User 'MyUser' deleted successfully
So my question is how to get only the last line without this x
The text you want is present in a text node and cannot be retrieved directly with Selenium since it only supports element nodes.
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:
String innerText = driver.findElement(By.cssSelector("div.success")).getAttribute("innerHTML");
String text = innerText.replaceFirst(".+?</button>([^>]+).*", "$1").trim();
Or with a piece of JavaScript:
String text = (String)((JavascriptExecutor)driver).executeScript(
"return document.querySelector('div.success > button').nextSibling.textContent;");
这篇关于如何使用selenium获取WebElement文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!