回答我自己的问题。
答案是实现一个ElementLocatorFactory,该元素允许您提供搜索上下文(含义是驱动程序或WebElement)。
public class SearchContextElementLocatorFactory implements ElementLocatorFactory { private final SearchContext context; public SearchContextElementLocatorFactory(SearchContext context) { this.context = context; } @Override public ElementLocator createLocator(Field field) { return new DefaultElementLocator(context, field); }}然后,在实例化页面对象时,使用此定位器工厂。
WebElement parent = driver.findElement(By.xpath("//div[contains(@class,'yui3-accordion-panel-content') and child::div[.='Sidebar']]"));SearchContextElementLocatorFactory elementLocatorFactory = new SearchContextElementLocatorFactory(parent);PageFactory.initElements(elementLocatorFactory, this);现在您的
@FindBy注释将相对于
parent。例如,获取主侧边栏
WebElement:
@FindBy(xpath = ".")WebElement sideBar;



