How to use findElements method of org.openqa.selenium.Interface SearchContext class

Best Selenium code snippet using org.openqa.selenium.Interface SearchContext.findElements

Source:WebElementWrapper.java Github

copy

Full Screen

...17 public final WebElement findElement(By by)18 {19 return Execute(() ->20 {21 List<WebElement> element = findNativeWebElement().findElements(by);22 WebElement result = element.get(0);23 if (result == null) {24 throw new NoSuchElementException(by.toString());25 }26 return result;27 });28 }29 public final List<WebElement> findElements(By by)30 {31 return Execute(() -> findNativeWebElement().findElements(by));32 }33 @FunctionalInterface34 public interface Function<WebElement>35 {36 WebElement invoke();37 }38 public WebElement invoke()39 {40 return invoke();41 }42 private <T> T Execute(Function<T> func)43 {44 for (int i = 5; i >= 0; i--)45 {...

Full Screen

Full Screen

Source:ByTest.java Github

copy

Full Screen

...39 @Test40 public void shouldUseFindsByNameToLocateElementsByName() {41 final AllDriver driver = mock(AllDriver.class);42 By.name("cheese").findElement(driver);43 By.name("peas").findElements(driver);44 verify(driver).findElementByName("cheese");45 verify(driver).findElementsByName("peas");46 verifyNoMoreInteractions(driver);47 }48 @Test49 public void shouldUseXPathToFindByNameIfDriverDoesNotImplementFindsByName() {50 final OnlyXPath driver = mock(OnlyXPath.class);51 By.name("cheese").findElement(driver);52 By.name("peas").findElements(driver);53 verify(driver).findElementByXPath(".//*[@name = 'cheese']");54 verify(driver).findElementsByXPath(".//*[@name = 'peas']");55 verifyNoMoreInteractions(driver);56 }57 @Test58 public void fallsBackOnXPathIfContextDoesNotImplementFallsById() {59 OnlyXPath driver = mock(OnlyXPath.class);60 By.id("foo").findElement(driver);61 By.id("bar").findElements(driver);62 verify(driver).findElementByXPath(".//*[@id = 'foo']");63 verify(driver).findElementsByXPath(".//*[@id = 'bar']");64 verifyNoMoreInteractions(driver);65 }66 @Test67 public void doesNotUseXPathIfContextFindsById() {68 AllDriver context = mock(AllDriver.class);69 By.id("foo").findElement(context);70 By.id("bar").findElements(context);71 verify(context).findElementById("foo");72 verify(context).findElementsById("bar");73 verifyNoMoreInteractions(context);74 }75 @Test76 public void searchesByTagNameIfSupported() {77 AllDriver context = mock(AllDriver.class);78 By.tagName("foo").findElement(context);79 By.tagName("bar").findElements(context);80 verify(context).findElementByTagName("foo");81 verify(context).findElementsByTagName("bar");82 verifyNoMoreInteractions(context);83 }84 @Test85 public void searchesByXPathIfCannotFindByTagName() {86 OnlyXPath context = mock(OnlyXPath.class);87 By.tagName("foo").findElement(context);88 By.tagName("bar").findElements(context);89 verify(context).findElementByXPath(".//foo");90 verify(context).findElementsByXPath(".//bar");91 verifyNoMoreInteractions(context);92 }93 @Test94 public void searchesByClassNameIfSupported() {95 AllDriver context = mock(AllDriver.class);96 By.className("foo").findElement(context);97 By.className("bar").findElements(context);98 verify(context).findElementByClassName("foo");99 verify(context).findElementsByClassName("bar");100 verifyNoMoreInteractions(context);101 }102 @Test103 public void searchesByXPathIfFindingByClassNameNotSupported() {104 OnlyXPath context = mock(OnlyXPath.class);105 By.className("foo").findElement(context);106 By.className("bar").findElements(context);107 verify(context).findElementByXPath(108 ".//*[contains(concat(' ',normalize-space(@class),' '),' foo ')]");109 verify(context).findElementsByXPath(110 ".//*[contains(concat(' ',normalize-space(@class),' '),' bar ')]");111 verifyNoMoreInteractions(context);112 }113 @Test114 public void innerClassesArePublicSoThatTheyCanBeReusedElsewhere() {115 assertThat(new ByXPath("a").toString()).isEqualTo("By.xpath: a");116 assertThat(new ById("a").toString()).isEqualTo("By.id: a");117 assertThat(new ByClassName("a").toString()).isEqualTo("By.className: a");118 assertThat(new ByLinkText("a").toString()).isEqualTo("By.linkText: a");119 assertThat(new ByName("a").toString()).isEqualTo("By.name: a");120 assertThat(new ByTagName("a").toString()).isEqualTo("By.tagName: a");121 assertThat(new ByCssSelector("a").toString()).isEqualTo("By.cssSelector: a");122 assertThat(new ByPartialLinkText("a").toString()).isEqualTo("By.partialLinkText: a");123 }124 // See https://github.com/SeleniumHQ/selenium-google-code-issue-archive/issues/2917125 @Test126 public void testHashCodeDoesNotFallIntoEndlessRecursion() {127 By locator = new By() {128 @Override129 public List<WebElement> findElements(SearchContext context) {130 return null;131 }132 };133 locator.hashCode();134 }135 private interface AllDriver136 extends FindsById, FindsByLinkText, FindsByName, FindsByXPath, FindsByTagName,137 FindsByClassName, SearchContext {138 // Place holder139 }140 private interface OnlyXPath extends FindsByXPath, SearchContext {141 }142}...

Full Screen

Full Screen

Source:AppiumElementLocator.java Github

copy

Full Screen

...3738 public List<WebElement> apply(By by) {39 List<WebElement> result = new ArrayList<WebElement>();40 try {41 result.addAll(searchContext.findElements(by));42 } catch (StaleElementReferenceException ignored) {}43 if (result.size() > 0) {44 return result;45 } else {46 return null;47 }48 }49 }5051 private final SearchContext searchContext;52 private final boolean shouldCache;53 private final By by;54 private WebElement cachedElement;55 private List<WebElement> cachedElementList;56 57 private final TimeOutContainer timeOutContainer;5859 /**60 * Creates a new mobile element locator. It instantiates {@link WebElement}61 * using @AndroidFindBy (-s), @iOSFindBy (-s) and @FindBy (-s) annotation sets62 * 63 * @param searchContext64 * The context to use when finding the element65 * @param field66 * The field on the Page Object that will hold the located value67 */68 AppiumElementLocator(SearchContext searchContext, Field field,69 TimeOutContainer timeOutContainer) {70 this.searchContext = searchContext;71 // All known webdrivers implement HasCapabilities72 Capabilities capabilities = ((HasCapabilities) unpackWebDriverFromSearchContext()).73 getCapabilities();74 75 String platform = String76 .valueOf(capabilities.getCapability(77 MobileCapabilityType.PLATFORM_NAME));78 String automation = String79 .valueOf(capabilities.getCapability(80 MobileCapabilityType.AUTOMATION_NAME));81 82 String browser = (String) capabilities.getCapability(CapabilityType.BROWSER_NAME); 83 String app = (String) capabilities.getCapability(MobileCapabilityType.APP);84 85 boolean isBrowser = ((app == null || "".equals(app.trim())) && 86 (browser != null && !"".equals(browser.trim())));87 88 AppiumAnnotations annotations = new AppiumAnnotations(field, 89 platform, automation, isBrowser);90 this.timeOutContainer = timeOutContainer;91 shouldCache = annotations.isLookupCached();92 by = annotations.buildBy();93 }94 95 private WebDriver unpackWebDriverFromSearchContext(){96 WebDriver driver = null;97 if (searchContext instanceof WebDriver){98 driver = (WebDriver) searchContext;99 } 100 //Search context it is not only Webdriver. Webelement is search context too.101 //RemoteWebElement and MobileElement implement WrapsDriver102 if (searchContext instanceof WebElement){103 WebElement element = (WebElement) searchContext; //there can be something that 104 //implements WebElement interface and wraps original105 while (element instanceof WrapsElement){106 element = ((WrapsElement) element).getWrappedElement();107 }108 driver = ((WrapsDriver) element).getWrappedDriver();109 }110 return driver;111 }112 113 private void changeImplicitlyWaitTimeOut(long newTimeOut, TimeUnit newTimeUnit){114 unpackWebDriverFromSearchContext().manage().timeouts().implicitlyWait(newTimeOut, newTimeUnit); 115 }116 117 //This method waits for not empty element list using all defined by118 private List<WebElement> waitFor(){119 //When we use complex By strategies (like ChainedBy or ByAll)120 //there are some problems (StaleElementReferenceException, implicitly wait time out121 //for each chain By section, etc)122 try{123 changeImplicitlyWaitTimeOut(0, TimeUnit.SECONDS);124 FluentWait<By> wait = new FluentWait<By>(by);125 wait.withTimeout(timeOutContainer.getTimeValue(), timeOutContainer.getTimeUnitValue()); 126 return wait.until(new WaitingFunction(searchContext));127 }128 catch (TimeoutException e){129 return new ArrayList<WebElement>();130 }131 finally{132 changeImplicitlyWaitTimeOut(timeOutContainer.getTimeValue(), 133 timeOutContainer.getTimeUnitValue());134 }135 }136 137 /**138 * Find the element.139 */140 public WebElement findElement() {141 if (cachedElement != null && shouldCache) {142 return cachedElement;143 }144 List<WebElement> result = waitFor(); 145 if (result.size() == 0){146 String message = "Cann't locate an element by this strategy: " + by.toString(); 147 throw new NoSuchElementException(message); 148 }149 if (shouldCache) {150 cachedElement = result.get(0);151 } 152 return result.get(0);153 }154155 /**156 * Find the element list.157 */158 public List<WebElement> findElements() {159 if (cachedElementList != null && shouldCache) {160 return cachedElementList;161 }162 List<WebElement> result = waitFor();163 if (shouldCache) {164 cachedElementList = result;165 } 166 return result;167 }168} ...

Full Screen

Full Screen

Source:PageUtils.java Github

copy

Full Screen

...25 protected List<WebElement> findByClass(String className) {26 return findByClass(driver, className);27 }28 protected List<WebElement> findByClass(SearchContext context, String className) {29 return context.findElements(By.className(className));30 }31 // FIND BY CSS QUERY32 33 protected WebElement findOneByCss(String query) {34 return findOneByCss(driver, query);35 }36 protected WebElement findOneByCss(SearchContext context, String query) {37 return context.findElement(By.cssSelector(query));38 }39 protected List<WebElement> findByCss(String query) {40 return findByCss(driver, query);41 }42 protected List<WebElement> findByCss(SearchContext context, String query) {43 return context.findElements(By.cssSelector(query));44 }45 46 // FIND BY NAME47 48 protected WebElement findOneByName(String name) {49 return findOneByName(driver, name);50 }51 protected WebElement findOneByName(SearchContext context, String name) {52 return context.findElement(By.name(name));53 }54 // FIND BY XPATH55 56 protected List<WebElement> findByXPath(String xpath) {57 return findByXPath(driver, xpath);58 }59 60 protected List<WebElement> findByXPath(SearchContext context, String xpath) {61 return context.findElements(By.xpath(xpath));62 }63 // COUNT BY CLASS64 65 protected int countByClass(String className) {66 return countByClass(driver, className);67 }68 69 protected int countByClass(SearchContext context, String className) {70 List<WebElement> list = findByClass(context, className);71 if (list != null) {72 return list.size();73 }74 return 0;75 }...

Full Screen

Full Screen

Source:ByAngularRepeaterCell.java Github

copy

Full Screen

...54 + ByAngular.functions.get("findRepeaterElement"), context);55 }56 // meaningless57 @Override58 public List<WebElement> findElements(SearchContext searchContext) {59 throw new UnsupportedOperationException(60 "This locator zooms in on a single cell, findElements() is meaningless");61 }62 @Override63 public String toString() {64 return (exact ? "exactR" : "r") + "epeater(" + repeater + ").row(" + row65 + ").column(" + column + ")";66 }67}...

Full Screen

Full Screen

Source:ByAngularRepeaterRow.java Github

copy

Full Screen

...55 + "\n" + ByAngular.functions.get("findRepeaterRows"), context);56 }57 // meaningless58 @Override59 public List<WebElement> findElements(SearchContext searchContext) {60 throw new UnsupportedOperationException(61 "This locator zooms in on a single row, findElements() is meaningless");62 }63 @Override64 public String toString() {65 return (exact ? "exactR" : "r") + "epeater(" + repeater + ").row(" + row66 + ")";67 }68}...

Full Screen

Full Screen

Source:IElementFinder.java Github

copy

Full Screen

...12 * @param locator elements locator13 * @param timeout timeout for search14 * @return list of found elements15 */16 List<WebElement> findElements(By locator, long timeout);17 /**18 * Finds element19 * @param locator elements locator20 * @param timeout timeout for search21 * @throws org.openqa.selenium.NoSuchElementException if element was not found in time in desired state22 * @return found element23 */24 WebElement findElement(By locator, long timeout);25 default List<WebElement> findElements(By by) {26 return findElements(by, getDefaultTimeout());27 }28 default WebElement findElement(By by) {29 return findElement(by, getDefaultTimeout());30 }31 /**32 * @return default timeout for element waiting33 */34 long getDefaultTimeout();35}...

Full Screen

Full Screen

Source:SearchScope.java Github

copy

Full Screen

...14 <T> T await(Function<SearchScope, T> function);15 default DelegatingElement findElement(Supplier<By> by) {16 return new DelegatingElement(await((e) -> e.findElement(by.get())));17 }18 default List<DelegatingElement> findElements(Supplier<By> by) {19 return await((e) -> e.findElements(by.get()).stream().map(DelegatingElement::new).collect(Collectors.toList()));20 }21 default Optional<DelegatingElement> optionalElement(Supplier<By> by) {22 try {23 return Optional.of(findElement(by));24 } catch (NoSuchElementException ignored) {25 return Optional.empty();26 }27 }28 default boolean isPresent(Supplier<By> by) {29 return optionalElement(by).isPresent();30 }31}...

Full Screen

Full Screen

findElements

Using AI Code Generation

copy

Full Screen

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.ui.ExpectedConditions;6import org.openqa.selenium.support.ui.WebDriverWait;7import java.util.List;8public class FindElementsMethod {9 public static void main(String[] args) throws InterruptedException {10 System.setProperty("webdriver.chrome.driver", "C:\\Users\\joseph\\Downloads\\chromedriver_win32\\chromedriver.exe");11 WebDriver driver = new ChromeDriver();12 driver.manage().window().maximize();13 WebDriverWait wait = new WebDriverWait(driver, 10);14 driver.findElement(By.name("q")).sendKeys("Selenium");15 Thread.sleep(1000);16 wait.until(ExpectedConditions.visibilityOfAllElements(suggestions));17 System.out.println("Number of suggestions in search box: " + suggestions.size());18 for (WebElement suggestion : suggestions) {19 System.out.println(suggestion.getText());20 }21 driver.quit();22 }23}24import org.openqa.selenium.By;25import org.openqa.selenium.WebDriver;26import org.openqa.selenium.WebElement;27import org.openqa.selenium.chrome.ChromeDriver;28import org.openqa.selenium.support.ui.ExpectedConditions;29import org.openqa.selenium.support.ui.WebDriverWait;30public class FindElementMethod {31 public static void main(String[] args) throws InterruptedException {32 System.setProperty("webdriver.chrome.driver", "C:\\Users\\joseph\\Downloads\\chromedriver_win32\\chromedriver.exe");33 WebDriver driver = new ChromeDriver();34 driver.manage().window().maximize();35 WebDriverWait wait = new WebDriverWait(driver, 10);36 driver.findElement(By.name("q")).sendKeys("Selenium");37 Thread.sleep(1000);38 wait.until(ExpectedConditions.visibilityOf

Full Screen

Full Screen

findElements

Using AI Code Generation

copy

Full Screen

1package com.automation;2import java.util.List;3import org.openqa.selenium.By;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.WebElement;6import org.openqa.selenium.chrome.ChromeDriver;7public class FindElementsSearchContext {8 public static void main(String[] args) throws InterruptedException {9 System.setProperty("webdriver.chrome.driver", "C:\\Users\\Srikanth\\Downloads\\chromedriver.exe");10 WebDriver driver = new ChromeDriver();11 Thread.sleep(3000);12 List<WebElement> links = driver.findElements(By.tagName("a"));13 System.out.println("Total number of links in google page: "+links.size());14 for (WebElement link : links) {15 System.out.println(link.getText());16 }17 driver.close();18 }19}

Full Screen

Full Screen

Selenium 4 Tutorial:

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.

Chapters:

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

  6. 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.

  7. 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.

Selenium 101 certifications:

LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in Interface-SearchContext

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful