线程“main”中的异常java.lang.ClassCastException:类org.openqa.selenium.remote.ShadowRoot无法转换为类org.openqa.selenium.Web

问题描述 投票:0回答:1

我曾尝试在 selenium 中为 Shadow DOM 编写此程序,但出现此错误。关于如何纠正此错误的任何解决方案。

尝试了不同的方法重写代码并找到错误仍然存在的地方,但仍然出现错误。

异常

Exception in thread "main" java.lang.ClassCastException: class org.openqa.selenium.remote.ShadowRoot cannot be cast to class org.openqa.selenium.WebElement (org.openqa.selenium.remote.ShadowRoot and org.openqa.selenium.WebElement are in unnamed module of loader 'app')
    at practice.ShadowDomExample.main(ShadowDomExample.java:25)

CODE
package practice;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class ShadowDomExample {

    @SuppressWarnings("deprecation")
    public static void main(String[] args) throws InterruptedException {
        WebDriver driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

        driver.get("https://books-pwakit.appspot.com/");
        driver.manage().window().maximize();

        WebElement root_ShadowHost = driver.findElement(By.cssSelector("book-app[apptitle='BOOKS']"));


        JavascriptExecutor js = (JavascriptExecutor) driver;
        WebElement shadowDOM = (WebElement) js.executeScript("return arguments[0].shadowRoot", root_ShadowHost);


        WebElement appheader = shadowDOM.findElement(By.tagName("app-header"));


        WebElement apptoolbar = appheader.findElement(By.cssSelector("app-toolbar.toolbar-bottom"));


        WebElement bookinputdecorator = apptoolbar.findElement(By.tagName("book-input-decorator"));

        WebElement searchBox = (WebElement) js.executeScript("return arguments[0].querySelector(\"input[aria-label='Search Books']\")", bookinputdecorator);

        searchBox.sendKeys("Testing");

        System.out.println("Succesfully typed into the search box ");

        driver.quit();
    }
}
java selenium-webdriver testing automation
1个回答
0
投票

影子根不能投射到

WebElement
,它实际上不是
WebElement
,它是其他实例,其中js props不同。为了让你的代码正常工作,你应该获取第一个影子 DOM 子节点并将其转换为
WebElement

driver.get("https://books-pwakit.appspot.com/");
driver.manage().window().maximize();

WebElement shadowHost = driver.findElement(By.cssSelector("book-app[apptitle='BOOKS']"));
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement appHeader = (WebElement) js.executeScript("return arguments[0].shadowRoot.querySelector('app-header')", shadowHost);
WebElement bookInputDecorator = appHeader.findElement(By.tagName("book-input-decorator"));
WebElement searchBox = (WebElement) js.executeScript("return arguments[0].querySelector(\"input[aria-label='Search Books']\")", bookInputDecorator);
searchBox.sendKeys("Testing");
© www.soinside.com 2019 - 2024. All rights reserved.