Answering my own question.
The answer is to implement an ElementLocatorFactory that allows you to provide a search context (value, driver, or 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); } }
Then, when instantiating the page object, use this factory locator.
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);
Now your @FindBy annotations will refer to parent . For example, to get the main WebElement :
@FindBy(xpath = ".") WebElement sideBar;
source share