You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Page Factory模式下实现基于WebElement的可复用元素查找方法

在Page Factory中实现可复用的批量WebElement查找方案

核心思路

不用为每个批量元素重复编写@FindBy List<WebElement>,而是基于Page Factory的原生机制封装通用方法,既保留延迟加载、缓存特性,又实现复用。

实现步骤

  1. 在BasePage基类中封装通用查找方法
    利用Page Factory的ElementLocator接口,直接基于传入的By定位器生成元素列表,复用框架的元素查找逻辑:

    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.support.pagefactory.DefaultElementLocatorFactory;
    import org.openqa.selenium.support.pagefactory.ElementLocator;
    import org.openqa.selenium.support.pagefactory.FindByAnnotationLocator;
    import java.util.List;
    
    public class BasePage {
        protected WebDriver driver;
        private DefaultElementLocatorFactory locatorFactory;
    
        public BasePage(WebDriver driver) {
            this.driver = driver;
            this.locatorFactory = new DefaultElementLocatorFactory(driver);
            PageFactory.initElements(driver, this);
        }
    
        // 通用批量查找方法,接收By定位器,返回延迟加载的元素列表
        protected List<WebElement> findElements(By by) {
            ElementLocator locator = new FindByAnnotationLocator(locatorFactory, by);
            return locator.findElements();
        }
    }
    
  2. 在具体Page类中直接调用
    单个元素仍用@FindBy定义,批量元素直接调用基类方法,无需重复编写注解:

    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.support.FindBy;
    import java.util.List;
    
    public class HomePage extends BasePage {
        // 单个元素保持原有@FindBy定义
        @FindBy(xpath = "//*[@id='notification-icon']")
        private WebElement notificationIcon;
    
        // 批量元素直接调用通用方法,无需额外注解
        public List<WebElement> getNavigationMenuItems() {
            return findElements(By.xpath("//nav//ul/li"));
        }
    
        public List<WebElement> getProductCards() {
            return findElements(By.cssSelector(".product-card"));
        }
    
        public HomePage(WebDriver driver) {
            super(driver);
        }
    }
    

关键特性说明

  • 延迟加载:元素列表会在首次调用时才执行查找,和@FindBy List<WebElement>的行为一致
  • 缓存机制:默认沿用Page Factory的缓存策略(元素查找后会缓存,除非手动禁用)
  • 完全复用:所有需要批量查找的场景都可以调用这个通用方法,无需重复编写注解代码

内容的提问来源于stack exchange,提问作者NoNoNo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 13:51:01