首页 > 解决方案 > 如何使用包装元素初始化 WebElement

问题描述

在执行任何操作之前,我已遵循有关如何关闭随机打开的弹出窗口的教程:

https://www.vinsguru.com/selenium-webdriver-how-to-handle-annoying-random-popup-alerts/

这个想法是创建一个实现接口 InvocationHandler 的 ElementProxy 类。因此,代理的调用方法将在调用实际方法之前首先被调用。

因此,我们在对 WebElement 调用任何操作之前调用 checkForPopupAndKill。

然后我们用这个代理对象包装我们的常规 WebElement。我们基本上需要一个类,它有一个方法来接受 WebElement 并返回带有一些包装器的 WebElement。

在本教程中,他们使用包装器元素初始化页面对象的元素,如下所示:

//first init elements
        PageFactory.initElements(driver, pageobject);

        //then access all the WebElements and create a wrapper
        for(Field f:pageobject.getClass().getDeclaredFields()){
            if(f.getType().equals(WebElement.class)){
                boolean accessible = f.isAccessible();
                f.setAccessible(true);
                //reset the webelement with proxy object
                f.set(pageobject, ElementGuard.guard((WebElement) f.get(pageobject)));
                f.setAccessible(accessible);
            }  
        }

那是因为他们已经在页面对象中声明了带有@FindBy注释的文件,但是在我的框架中,我将元素声明如下:

WebElement elt = getSmartElement(By.cssSelector("#my_id"));

我的问题是,如何使用包装元素初始化我的元素?

提前致谢。

标签: seleniumselenium-webdriver

解决方案


您可以直接使用 ElementGuard,如此处所示,它使用代理包装实际的 WebElement。

WebElement elt = ElementGuard.guard(getSmartElement(By.cssSelector("#my_id")));


推荐阅读