Rajnish Kumar
Rajnish Kumar

Reputation: 2938

How to Sort WebElements in a ArrayList in WebDriver?

Please help how to sort below piece of code to find max,min and average ? Actually i want to Navigate to the question that has the most views and use Selenium to take a screen shot of the question's page i am using https://stackoverflow.com/ home page as my sample page

List<WebElement> views = driver.findElements(By.xpath("//*[@class='mini-counts']/span"));
System.out.println("Size is = " + views.size());

String maxvalue = "maxvalue after sorting";
for(int i=2;i< views.size();i+=3){
    if(views.get(i).getText().equals(maxvalue)){
        views.get(i).click();
        File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(scrFile, new File(System.getProperty("user.dir")+"\\Screenshots\\"+"most_views.png"));
    }

Upvotes: 0

Views: 2546

Answers (1)

Ajinkya
Ajinkya

Reputation: 22710

You can use comparator, create comparator class like

public class ViewComparator implements Comparator {

    @Override
    public int compare(WebElement w1, WebElement w2) {
       // extract view count from WebElement and compare it
    }
}

and then use it like

Collections.sort(views, new ViewCountComparator());

this will sort the list based on view count and then you can take first/last WebElement to get min/max value.

Upvotes: 1

Related Questions