xpathselenium-webdriverpageobjectsfindby

Iterate through all elements xpath using @Findby in java


I have started using Page factory, and now i need to provide xpath in @FindBy. It will be great if someone can provide any suggestion or reference on how to pass variable in xpath using @Findby.

Element which i want to replace with @Findby annotation

for(i=1; i <= liElements.size(); i++) {
   WebElement linkElement = driver.findElement(By.xpath("//li[" + i + "]/div//a[contains(@class, 'btn-mini')]"));
   linkElement.click(); 
}

Thanks a lot in advance for your help.


Solution

  • Regarding your question around parametrised FindBy - this is not possible as annotations are constant values. Take a look here - Can the annotation variables be determined at runtime?

    In this particular case you can find a list of the elements in FindBy:

    @FindBy(xpath = "//li/div//a[contains(@class, 'btn-mini')]")
    private List<WebElement> links;
    

    Then you can iterate through them like this:

    for(WebElement link : links) {
        link.click(); 
    }
    

    So you will click links found by that xPath one by one.