0

I have a List of Webelements out which a random element is selected. Now having a random webelement, i need to locate all the child elements in it. How can i acheive this in pagefactory.

In selenium, this was working:

List<WebElement> listOfElements = driver.findElements(By.xpath("//locator"));

WebElement randomElement = // Code to get a random element out of this list.

String title = randomElement.findElement(By.xpath(".//[@id='title']"));

In page factory, i have tried:

@FindBy(xpath="//locator")

List<WebElement> listOfElements;

@FindBy(id="title");

WebElement title;


WebElement randomElement = // Code to get a random element out of this list.

Stuck at how to fetch title in the random element using page factory annotations.

I know this would work:

String title = randomElement.findElement(By.xpath(".//[@id='title']"));

As i am using page factory annotations in the entire project, is there a way to achieve the same.

2 Answers 2

0

You make a public method in your page object that returns a list of webelements.

public List<WebElement> getTitles(WebElement randomElement) {
    return randomElement.findElements(by.id("title"));
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Bill. But i wanted to know whether there is any way to do randomElement.findElements(LOCATOR) using annotations like FindBy, FindBys, FindAll etc.
Since FindBy can only use constant or literal parameters, you can only read an array list, then use random logic to select from that list.
Ok, Thanks Bill.
0

Probably too late for you, but in case its helpful to anyone else: It is possible to do this, but not simple and requires customising some of WebDriver's inner classes.

I discussed how I went about solving this problem using 'block' classes in a blog post earlier this year. This not not something trivial, but there is a github project containing the code that I used if you want to dig in to to use yourself.

In essence I use each of the located WebElement to generate a new 'PageObject' class called a block. A long as each of the random elements is the same, you can use the PageFactory notation to find the child WebElements.

Do note, there is significant overhead in all of this, so if you are merely trying to get the title you would be much better off using the stream API with a chained findElements() call.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.