
qaf虽原生不支持selenium的@findall注解,但可通过手动调用pagefactory.initelements实现兼容,从而灵活定位满足任一条件(如多个class、id或xpath)的多个webelement。
qaf虽原生不支持selenium的@findall注解,但可通过手动调用pagefactory.initelements实现兼容,从而灵活定位满足任一条件(如多个class、id或xpath)的多个webelement。
在Qmetry Automation Framework(QAF)中,开发者常需基于多个选择器条件(例如同时匹配 class="class1" 或 class="class2")批量定位Web元素。与Selenium原生支持的 @FindAll 注解不同,QAF默认仅原生支持其自定义的 @FindBy 和 @FindBys(对应“与”逻辑),并不直接支持 @FindAll(对应“或”逻辑)。但得益于QAF对Selenium原生注解的良好兼容性,我们仍可无缝集成 @FindAll,只需补充一行关键初始化代码。
✅ 正确使用 @FindAll 的步骤
-
引入Selenium注解包:确保导入
org.openqa.selenium.support.FindAll和org.openqa.selenium.support.FindBy; -
在页面类构造函数中显式初始化:调用
PageFactory.initElements(driver, this),以激活Selenium注解处理器; -
声明目标元素列表:使用
@FindAll组合多个@FindBy条件。
示例代码如下:
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindAll;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.qmetry.qaf.automation.ui.WebDriverBaseTestPage;
import com.qmetry.qaf.automation.ui.WebDriverTestPage;
public class MyPage extends WebDriverBaseTestPage<webdrivertestpage> {
@FindAll({
@FindBy(className = "class1"),
@FindBy(className = "class2")
})
private List<webelement> elementsWithEitherClass1OrClass2;
public MyPage() {
// 关键:启用Selenium注解解析(QAF默认不自动调用)
PageFactory.initElements(getDriver(), this);
}
// 可选:封装获取逻辑,增强可读性与复用性
public List<webelement> getElementsWithClass1OrClass2() {
return elementsWithEitherClass1OrClass2;
}
}</webelement></webelement></webdrivertestpage>
⚠️ 注意事项
- ❗
PageFactory.initElements(...)必须在构造函数中执行,且需传入当前getDriver()实例(而非driver字段,因QAF中推荐使用getDriver()获取线程安全的WebDriver实例); - ❗ 避免混用QAF原生
com.qmetry.qaf.automation.ui.annotations.FindBy与Seleniumorg.openqa.selenium.support.FindBy—— 二者注解处理器不同,混合使用可能导致初始化失败; - ✅
@FindAll中的多个@FindBy是 OR 关系(即匹配任一条件即纳入结果),而@FindBys是 AND 关系(需同时满足所有条件),请按语义准确选用; - ✅ 若需更复杂的定位逻辑(如动态XPath组合、属性正则匹配),建议配合QAF内置的
Locator工具类或getDriver().findElements(...)手动构建,保持灵活性与可维护性。
综上,QAF并非排斥Selenium标准能力,而是通过显式初始化桥接二者优势。合理运用 @FindAll,可在保持QAF工程结构的同时,高效解决多条件“或”匹配场景,显著提升页面对象模型(POM)的表达力与复用性。










