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

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

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
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:/​/​siteproxy.ruqli.workers.dev:443/​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
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
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
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
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
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
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

StackOverFlow community discussions

Questions
Discussion

How to automate drag &amp; drop functionality using Selenium WebDriver Java

Wait for page load in Selenium

maven: Multiple annotations found at this line:

Selenium WebDriver and InternetExplorer

WebDriverException: unknown error: failed to change window state to maximized, current state is normal with Chrome 70 &amp; Chromedriver 2.43 on MAC OS X

Selecting an item from a combo box selenium driver with java

Selenium Webdriver(JAVA) Nested Elements

How to handle Javascript Alert/pop up window in selenium webdriver

Wait for an image to be fully loaded Selenium WebDriver

MacOS Catalina(v 10.15.3): Error: “chromedriver” cannot be opened because the developer cannot be verified. Unable to launch the chrome browser

There is a page documenting Advanced User Interactions; which has a lot of great examples on how to generate a sequence of actions, you can find it here

// Configure the action
Actions builder = new Actions(driver);

builder.keyDown(Keys.CONTROL)
   .click(someElement)
   .click(someOtherElement)
   .keyUp(Keys.CONTROL);

// Then get the action:
Action selectMultiple = builder.build();

// And execute it:
selectMultiple.perform();   

or

Actions builder = new Actions(driver);

Action dragAndDrop = builder.clickAndHold(someElement)
   .moveToElement(otherElement)
   .release(otherElement)
   .build();

dragAndDrop.perform();
https://stackoverflow.com/questions/14210051/how-to-automate-drag-drop-functionality-using-selenium-webdriver-java

Blogs

Check out the latest blogs from LambdaTest on this topic:

16 Best Practices Of CI/CD Pipeline To Speed Test Automation

Every software project involves some kind of ‘processes’ & ‘practices’ for successful execution & deployment of the project. As the size & scale of the project increases, the degree of complications also increases in an exponential manner. The leadership team should make every possible effort to develop, test, and release the software in a manner so that the release is done in an incremental manner thereby having minimal (or no) impact on the software already available with the customer.

Why Vertical Text Orientation Is A Nightmare For Cross Browser Compatibility?

The necessity for vertical text-orientation might not seem evident at first and its use rather limited solely as a design aspect for web pages. However, many Asian languages like Mandarin or Japanese scripts can be written vertically, flowing from right to left or in case of Mongolian left to right. In such languages, even though the block-flow direction is sideways either left to right or right to left, letters or characters in a line flow vertically from top to bottom. Another common use of vertical text-orientation can be in table headers. This is where text-orientation property becomes indispensable.

Why Selenium WebDriver Should Be Your First Choice for Automation Testing

Developed in 2004 by Thoughtworks for internal usage, Selenium is a widely used tool for automated testing of web applications. Initially, Selenium IDE(Integrated Development Environment) was being used by multiple organizations and testers worldwide, benefits of automation testing with Selenium saved a lot of time and effort. The major downside of automation testing with Selenium IDE was that it would only work with Firefox. To resolve the issue, Selenium RC(Remote Control) was used which enabled Selenium to support automated cross browser testing.

Best 9 PHP Frameworks In 2019 For Test Automation

PHP is one of the most popular scripting languages used for server-side web development. It is used by multiple organizations, especially for content management sites like WordPress. If you are thinking about developing a web application using PHP, you will also need one of the best php frameworks in 2019 for testing of your application. You can perform visual and usability testing manually but for functionality, acceptance and unit testing, cross browser testing, an automated PHP framework will help pace the test cycles drastically. In this article, we will compare the best 9 PHP frameworks in 2019 for test automation that eases the job of a tester and ensures faster deployment of your application.

Best Usability Testing Tools For Your Website

When a user comes to your website, you have time in seconds to influence them. Web usability is the key to gain quick trust, brand recognition and ensure user retention.

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