如何解决由于存在另一个标签,无法从 selenium 中的 span 中捕获文本
当我通过提供以下代码捕获文本时
String str1 = driver.findElement(By.xpath("//[@class='errorNotification']//span[2]")).getAttribute("innerHTML");
System.out.println("innerHTML: "+str1);
所以我得到如下输出
innerHTML://i class="fa fa-times" style="font-size: 14px"></i Please enter user password!
我只想要文本“请输入用户密码”而不是整个标签。
我的 DOM 看起来像
<div class="errorNotification">
<span class="notificationCloseBtn" title="Close Notification">x</span>
<span style="font-size: 13px">
<i class="fa fa-times" style="font-size: 14px"></i> Please enter user password!
</span>
</div>
解决方法
而不是这个:
String str1 = driver.findElement(By.xpath("//[@class='errorNotification']//span[2]")).getAttribute("innerHTML");
使用这个:
String str1 = driver.findElement(By.cssSelector("div.errorNotification span.notificationCloseBtn+span")).getText()
System.out.println("Str 1 has : " +str1);
说明:
您正在使用 getAttribute("innerHTML");
它将返回 entire inner HTLM
(对于当前节点)以及 HTML tags
和 text
,而且您似乎只想获取文本,因此,Selenium 具有内置方法 getText()
来检索节点之间的文本。
看看是否有效
String text = driver.findElement(By.xpath("//div[@class='errorNotification']/span[not(@class='notificationCloseBtn')]")).getText();
System.out.println(text);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。