For Example,
WebElement parentEle = driver.findElement(By.id("xyz"));
WebElement childEle = parentEle.findElement(By.id("abc"));
childEle.click();
In the above example, We are finding childEle with in parentEle. How can we achieve this using @FindBy annotation (in conjunction with PageFactory)
Using @FindBy, a list of elements will be created as follows: @FindBy(how = CSS, using = "option") private List<WebElement> webElements; Each entry in the dropdown is represented by its' own webElement. The above just means you now have a list of WebElements, but you do not have access to the labels themselves.
@FindBy annotation in Page Factory The @FindBy annotation is used to declare and initialize web element variables using the desired web locators in Selenium. Hence, you can find the web elements using popular locators like ID, Name, Link Text, Class Name, etc.
In Page Factory, testers use @FindBy annotation. The initElements method is used to initialize web elements. @FindBy: An annotation used in Page Factory to locate and declare web elements using different locators. Below is an example of declaring an element using @FindBy.
@FindBys({ @FindBy(how = How.NAME, using = "username"), @FindBy(how = How.NAME, using = "password") }) private List<WebElement> bothcriteria; The bothcriteria list should contain 0 elements, as there is no element that has both a name attribute with the value username and a name attribute with the value password.
First of all why do you need to find child from a parent if the child has a UNIQUE id? The main purpose of id is to provide the flexibility of finding the element with a unique selector.
In case if the child element is really nested to other, find that with xpath. I often use that.
@FindBy(how = How.XPATH, using = "//something/something")
private WebElement TestElement;
Or with ID
@FindBy(how = How.ID, using = "abc")
private WebElement TestElement;
This can be achieved in couple of steps:
//identify parent element with @FindBy annotation
1) @FindBy(className="locator")
List<WebElement> parent;
//loop through each parent to get child(<li> in your case) of each parent
2) for(WebElement list_items:Parent){
list_items.findElement(By.xpath("child locator"));
I had used this approach and was able to achieve the desired results. Hope this explains your query as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With