Best Selenium code snippet using org.openqa.selenium.support.pagefactory.Interface ElementLocator.findElements
Source:TableElementImpl.java  
...35        return asList(new ColumnHeadingToClassFieldMappingAdapter<>(type));36    }37    @Override38    public <T> List<T> asList(final RowAdapter<T> adapter) {39        final List<WebElement> columnHeaderElements = cache.getElement().findElements(columnFinder);40        final List<WebElement> rows = findAllRows();41        final List<T> mappedRows = new LinkedList<>();42        for (final WebElement row : rows) {43            final List<WebElement> cells = row.findElements(cellLocator);44            mappedRows.add(adapter.adapt(columnHeaderElements, cells));45        }46        return mappedRows;47    }48    @Override49    public <T> List<T> asPivot(final CellAdapter<T> adapter) {50        final CellVisitor<List<T>> collatingCellAdapter = new CellVisitor<List<T>>() {51            final List<T> adaptedCells = new LinkedList<>();52            @Override53            public void visit(final List<WebElement> columnHeaders, final WebElement rowHeader, final WebElement cell) {54                // Adapt the first column header only - maintains backward55                // compatability for CellAdapter56                adaptedCells.add(adapter.adapt(columnHeaders.get(0), rowHeader, cell));57            }58            @Override59            public List<T> result() {60                return adaptedCells;61            }62            @Override63            public boolean isFinished() {64                // process all cells65                return false;66            }67        };68        return visitCells(collatingCellAdapter);69    }70    @Override71    public <T> List<T> asPivot(final MultiCellAdapter<T> adapter) {72        final List<T> adaptedCells = new LinkedList<>();73        final List<WebElement> rows = findAllRows();74        for (final WebElement row : rows) {75            final List<WebElement> cells = row.findElements(cellLocator);76            final WebElement rowHeader = cells.remove(0);77            // +1 for index to ordinal78            // +roHeaderColspan to skip the row header column(s)79            final int columnOrdinalOffset = 1 + rowHeaderColspan;80            for (int i = 0; i < cells.size(); i++) {81                final List<WebElement> columnHeaders = cache.getElement().findElements(byColumn(i + columnOrdinalOffset));82                final WebElement cell = cells.get(i);83                adaptedCells.add(adapter.adapt(columnHeaders, rowHeader, cell));84            }85        }86        return adaptedCells;87    }88    private By byColumn(final int ordinal) {89        return By.cssSelector(String.format("thead th:nth-child(%s)", ordinal));90    }91    private List<WebElement> findAllRows() {92        return cache.getElement().findElements(rowLocator);93    }94    public List<WebElement> searchForRows(final Condition<WebElement> condition) {95        final Iterable<WebElement> allRows = Iterables.filter(findAllRows(), condition);96        return Lists.newArrayList(allRows);97    }98    @Override99    public MatchingCell firstMatch(final CellAdapter<Boolean> matcher) throws NoSuchElementException {100        final CellVisitor<MatchingCell> firstMatchVisitor = new CellVisitor<MatchingCell>() {101            private MatchingCell firstMatch = null;102            @Override103            public void visit(final List<WebElement> columnHeaders, final WebElement rowHeader, final WebElement cell) {104                for (final WebElement columnHeader : columnHeaders) {105                    if (matcher.adapt(columnHeader, rowHeader, cell)) {106                        firstMatch = new MatchingCell() {107                            @Override108                            public WebElement getColumn() {109                                return columnHeader;110                            }111                            @Override112                            public WebElement getRow() {113                                return rowHeader;114                            }115                            @Override116                            public WebElement getCell() {117                                return cell;118                            }119                        };120                        // We're done121                        return;122                    }123                }124            }125            @Override126            public MatchingCell result() {127                return firstMatch;128            }129            @Override130            public boolean isFinished() {131                return firstMatch != null;132            }133        };134        final MatchingCell result = visitCells(firstMatchVisitor);135        if (result == null) {136            throw new NoSuchElementException("No matching cell found");137        }138        return result;139    }140    private <T> T visitCells(final CellVisitor<T> v) {141        final List<WebElement> rows = findAllRows();142        for (final WebElement row : rows) {143            final List<WebElement> cells = row.findElements(cellLocator);144            final WebElement rowHeader = cells.remove(0);145            // +1 for index to ordinal146            // +roHeaderColspan to skip the row header column(s)147            final int columnOrdinalOffset = 1 + rowHeaderColspan;148            for (int i = 0; i < cells.size(); i++) {149                final List<WebElement> columnHeaders = cache.getElement().findElements(byColumn(i + columnOrdinalOffset));150                final WebElement cell = cells.get(i);151                v.visit(columnHeaders, rowHeader, cell);152                if (v.isFinished()) {153                    return v.result();154                }155            }156        }157        return v.result();158    }159    private interface CellVisitor<T> {160        /**161         * Visit a particular cell162         *163         * @param columnHeaders...Source:ControlFieldDecorator.java  
...41            return proxyForLocator(loader, fieldType, locator);42        } else if (List.class.isAssignableFrom(fieldType)) {43            Class<?> erasureClass = getErasureClass(field);44            if(erasureClass.equals(WebElement.class))45                return locator.findElements();46            return proxyForListLocator(loader, erasureClass, locator);47        } else {48            return null;49        }50    }5152    private Class getErasureClass(Field field) {53        Type genericType = field.getGenericType();54        if (!(genericType instanceof ParameterizedType)) {55            return null;56        }57        return (Class) ((ParameterizedType) genericType).getActualTypeArguments()[0];58    }59
...Source:ControlListHandler.java  
...40    @Override41    public Object invoke(Object o, Method method, Object[] objects) throws Throwable {42        List<Object> wrappedList = new ArrayList<Object>();43        Constructor<?> cons = wrappingType.getConstructor(WebElement.class);44        for (WebElement element : locator.findElements()) {45            Object thing = cons.newInstance(element);46            wrappedList.add(wrappingType.cast(thing));47        }48        try {49            return method.invoke(wrappedList, objects);50        } catch (InvocationTargetException e) {51            // Unwrap the underlying exception52            throw e.getCause();53        }54    }55}...Source:ElementListHandler.java  
...21    @Override22    public Object invoke(Object o, Method method, Object[] objects) throws Throwable {23        List<Object> wrappedList = new ArrayList<Object>();24        Constructor<?> cons = wrappingType.getConstructor(WebElement.class);25        for (WebElement element : locator.findElements()) {26            Object thing = cons.newInstance(element);27            wrappedList.add(wrappingType.cast(thing));28        }29        try {30            return method.invoke(wrappedList, objects);31        } catch (InvocationTargetException e) {32            // Unwrap the underlying exception33            throw e.getCause();34        }35    }36}...Source:LocatingCustomElementListHandler.java  
...17        this.clazz = clazz;18        this.elementContainer = elementContainer;19    }20    public Object invoke(Object object, Method method, Object[] objects) throws Throwable {21        List<WebElement> elements = locator.findElements();22        List<CustomWebElementInterface> customs = new ArrayList<>();23        for (WebElement element : elements) {24            customs.add(WrapperFactory.createInstance(clazz, element, elementContainer));25        }26        try {27            return method.invoke(customs, objects);28        } catch (InvocationTargetException e) {29            throw e.getCause();30        }31    }32}...Source:CustomElementListHandler.java  
...11	    this.locator = locator;12	  }13	 14	public Object invoke(Object object, Method method, Object[] objects) throws Throwable {15	    List<WebElement> elements = locator.findElements();16	    try {17	      return method.invoke(elements, objects);18	    } catch (InvocationTargetException e) {19	      // Unwrap the underlying exception20	      throw e.getCause();21	    }22	  }23}...Source:ElementLocator.java  
...4public abstract interface ElementLocator5{6  public abstract WebElement findElement();7  8  public abstract List<WebElement> findElements();9}...findElements
Using AI Code Generation
1import org.openqa.selenium.By;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.WebElement;4import org.openqa.selenium.chrome.ChromeDriver;5import org.openqa.selenium.support.FindBy;6import org.openqa.selenium.support.FindBys;7import org.openqa.selenium.support.PageFactory;8import org.openqa.selenium.support.pagefactory.ElementLocator;9import org.openqa.selenium.support.pagefactory.ElementLocatorFactory;10import java.util.List;11public class FindElements {12    public static void main(String[] args) {13        System.setProperty("webdriver.chrome.driver", "C:\\Users\\Kalyani\\Downloads\\chromedriver_win32\\chromedriver.exe");14        WebDriver driver = new ChromeDriver();15        driver.manage().window().maximize();16        AmazonPage amazonPage = new AmazonPage(driver);17        List<WebElement> allElements = amazonPage.getAllElements();18        System.out.println(allElements.size());19        for (WebElement element : allElements) {20            System.out.println(element.getText());21        }22        driver.quit();23    }24    public static class AmazonPage {25        private final ElementLocatorFactory finder;26        private List<WebElement> allElements;27        public AmazonPage(WebDriver driver) {28            this.finder = new CustomElementLocatorFactory(driver);29            PageFactory.initElements(finder, this);30        }31        public List<WebElement> getAllElements() {32            return allElements;33        }34    }35    public static class CustomElementLocatorFactory implements ElementLocatorFactory {36        private final WebDriver driver;37        public CustomElementLocatorFactory(WebDriver driver) {38            this.driver = driver;39        }40        public ElementLocator createLocator(Field field) {41            return new CustomElementLocator(driver, field);42        }43    }44    public static class CustomElementLocator implements ElementLocator {45        private final WebDriver driver;46        private final Field field;47        public CustomElementLocator(WebDriver driver, Field field) {48            this.driver = driver;49            this.field = field;50        }51        public WebElement findElement() {52            return null;53        }54        public List<WebElement> findElements() {55            return driver.findElements(By.xpath(field.getAnnotation(FindBys.class).value()[0].xpath()));56        }57    }58}findElements
Using AI Code Generation
1import org.openqa.selenium.WebDriver;2import org.openqa.selenium.WebElement;3import org.openqa.selenium.chrome.ChromeDriver;4import org.openqa.selenium.support.FindBy;5import org.openqa.selenium.support.FindBys;6import org.openqa.selenium.support.PageFactory;7import org.openqa.selenium.support.pagefactory.DefaultElementLocator;8import org.openqa.selenium.support.pagefactory.DefaultFieldDecorator;9import java.lang.reflect.Field;10import java.util.List;11public class FindElements {12    @FindBy(id = "id1")13    private List<WebElement> list1;14    @FindBy(id = "id2")15    private List<WebElement> list2;16    @FindBys({17            @FindBy(id = "id3"),18            @FindBy(id = "id4")19    })20    private List<WebElement> list3;21    @FindBys({22            @FindBy(id = "id5"),23            @FindBy(id = "id6")24    })25    private List<WebElement> list4;26    public static void main(String[] args) {27        System.setProperty("webdriver.chrome.driver", "C:\\Users\\User\\Downloads\\chromedriver_win32\\chromedriver.exe");28        WebDriver driver = new ChromeDriver();29        FindElements findElements = new FindElements();30        PageFactory.initElements(driver, findElements);31        System.out.println("list1.size() = " + findElements.list1.size());32        System.out.println("list2.size() = " + findElements.list2.size());33        System.out.println("list3.size() = " +findElements
Using AI Code Generation
1import org.openqa.selenium.By;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.WebElement;4import org.openqa.selenium.firefox.FirefoxDriver;5import org.openqa.selenium.support.FindBy;6import org.openqa.selenium.support.How;7import org.openqa.selenium.support.PageFactory;8public class TestFindElements {9    public static void main(String[] args) {10        WebDriver driver = new FirefoxDriver();11        GooglePage page = PageFactory.initElements(driver, GooglePage.class);12        page.searchFor("Cheese");13        driver.quit();14    }15    public static class GooglePage {16        @FindBy(how = How.NAME, using = "q")17        private WebElement query;18        public void searchFor(String text) {19            query.sendKeys(text);20            query.submit();21        }22    }23}findElements
Using AI Code Generation
1public class ElementLocatorHelper {2    private final ElementLocator locator;3    public ElementLocatorHelper(ElementLocator locator) {4        this.locator = locator;5    }6    public List<IWebElement> FindElements() {7        return locator.findElements();8    }9}LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.
Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.
What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.
Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.
Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.
How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.
Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.
Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.
LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.
Get 100 minutes of automation test minutes FREE!!
