繁体   English   中英

如何通过selenium检查伪元素是否存在

[英]How to check if a pseudo element exists or not through selenium

我需要知道我们是否可以找到伪元素的存在,例如::after 和::before

我的目标只是在存在时返回真或假。

但是,它不能使用:

browser.driver.findElements(by.id('id')).size != 0

或者

return !driver.findElements(by).isEmpty(); 

因为它们是伪元素,不能通过任何 CS 或 XPATH 定位器定位

这是我的 HTML 有::after

 <div class="parent-class"> <span class="child-class">Archive::after </span>::after </div>

这是我的 HTML 没有::after

 <div class="parent-class"> <span class="child-class">Archive::after </span> </div>

注意:我只需要验证 DIV 标签中的 ::after 而不是 SPAN 标签

是的,伪元素不能通过路径或 CSS 定位器定位。 但是,作为替代方案,您可以提取父元素的内部 HTML 并验证它是否包含“::after”文本。

有两种方法可以做到这一点。 对于上述场景,

WebElement element = browser.driver.findElement(By.className('parent-class'))
String innerHTMLText = element.getAttribute('innerHTML');
if (innerHTMLText.contains("::after")){
   // Bingo !!
}

要不然

WebElement element = browser.driver.findElement(By.className('parent-class'))
JavascriptExecutor js = (JavascriptExecutor)driver;
String innerHTMLText = js.executeScript("return arguments[0].innerHTML;", element);
if (innerHTMLText.contains("::after")){
   // Bingo !!
}

编辑 1

If you need to verify if only the div tag is having the pseudo-element you can get the span tag's HTML, get parent tag's HTML, remove span tag inner HTML from parent tag's HTML. 核实。

String divHTMLText = browser.driver.findElement(By.className('parent-class')).getAttribute('innerHTML');
String spanHTMLText = browser.driver.findElement(By.className('child-class')).getAttribute('innerHTML');
// replace all the whitespaces first for good measure
divHTMLText = divHTMLText.replaceAll("\\s+","")
spanHTMLText = spanHTMLText.replaceAll("\\s+","")
// replace the child html from parent's html with empty. which leaves us with the parent html code.
String divOnlyHTML = divHTMLText.replace(spanHTMLText, "");

if (divOnlyHTML.contains("::after")){
   // Bingo !!
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM