Best Selenium code snippet using org.openqa.selenium.Interface SearchContext
Source:AjaxElementLocator.java
1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements. See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership. The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License. You may obtain a copy of the License at8//9// http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.support.pagefactory;18import org.openqa.selenium.NoSuchElementException;19import org.openqa.selenium.SearchContext;20import org.openqa.selenium.WebElement;21import org.openqa.selenium.support.ui.Clock;22import org.openqa.selenium.support.ui.SlowLoadableComponent;23import org.openqa.selenium.support.ui.SystemClock;24import java.lang.reflect.Field;25import java.util.ArrayList;26import java.util.List;27/**28 * An element locator that will wait for the specified number of seconds for an element to appear,29 * rather than failing instantly if it's not present. This works by polling the UI on a regular30 * basis. The element returned will be present on the DOM, but may not actually be visible: override31 * {@link #isElementUsable(WebElement)} if this is important to you.32 *33 * Because this class polls the interface on a regular basis, it is strongly recommended that users34 * avoid locating elements by XPath.35 */36public class AjaxElementLocator extends DefaultElementLocator {37 protected final int timeOutInSeconds;38 private final Clock clock;39 /**40 * Use this constructor in order to process custom annotaions.41 *42 * @param context The context to use when finding the element43 * @param timeOutInSeconds How long to wait for the element to appear. Measured in seconds.44 * @param annotations AbstractAnnotations class implementation45 */46 public AjaxElementLocator(SearchContext context, int timeOutInSeconds, AbstractAnnotations annotations) {47 this(new SystemClock(), context, timeOutInSeconds, annotations);48 }49 public AjaxElementLocator(Clock clock, SearchContext context, int timeOutInSeconds,50 AbstractAnnotations annotations) {51 super(context, annotations);52 this.timeOutInSeconds = timeOutInSeconds;53 this.clock = clock;54 }55 /**56 * Main constructor.57 *58 * @param searchContext The context to use when finding the element59 * @param field The field representing this element60 * @param timeOutInSeconds How long to wait for the element to appear. Measured in seconds.61 */62 public AjaxElementLocator(SearchContext searchContext, Field field, int timeOutInSeconds) {63 this(new SystemClock(), searchContext, field, timeOutInSeconds);64 }65 public AjaxElementLocator(Clock clock, SearchContext searchContext, Field field, int timeOutInSeconds) {66 this(clock, searchContext, timeOutInSeconds, new Annotations(field));67 }68 /**69 * {@inheritDoc}70 *71 * Will poll the interface on a regular basis until the element is present.72 */73 @Override74 public WebElement findElement() {75 SlowLoadingElement loadingElement = new SlowLoadingElement(clock, timeOutInSeconds);76 try {77 return loadingElement.get().getElement();78 } catch (NoSuchElementError e) {79 throw new NoSuchElementException(80 String.format("Timed out after %d seconds. %s", timeOutInSeconds, e.getMessage()),81 e.getCause());82 }83 }84 /**85 * {@inheritDoc}86 *87 * Will poll the interface on a regular basis until at least one element is present.88 */89 @Override90 public List<WebElement> findElements() {91 SlowLoadingElementList list = new SlowLoadingElementList(clock, timeOutInSeconds);92 try {93 return list.get().getElements();94 } catch (NoSuchElementError e) {95 return new ArrayList<>();96 }97 }98 /**99 * By default, we sleep for 250ms between polls. You may override this method in order to change100 * how it sleeps.101 *102 * @return Duration to sleep in milliseconds103 */104 protected long sleepFor() {105 return 250;106 }107 /**108 * By default, elements are considered "found" if they are in the DOM. Override this method in109 * order to change whether or not you consider the element loaded. For example, perhaps you need110 * the element to be displayed:111 *112 * <pre>{@code113 * return element.isDisplayed();114 * }</pre>115 *116 * @param element The element to use117 * @return Whether or not it meets your criteria for "found"118 */119 protected boolean isElementUsable(WebElement element) {120 return true;121 }122 private class SlowLoadingElement extends SlowLoadableComponent<SlowLoadingElement> {123 private NoSuchElementException lastException;124 private WebElement element;125 public SlowLoadingElement(Clock clock, int timeOutInSeconds) {126 super(clock, timeOutInSeconds);127 }128 @Override129 protected void load() {130 // Does nothing131 }132 @Override133 protected long sleepFor() {134 return AjaxElementLocator.this.sleepFor();135 }136 @Override137 protected void isLoaded() throws Error {138 try {139 element = AjaxElementLocator.super.findElement();140 if (!isElementUsable(element)) {141 throw new NoSuchElementException("Element is not usable");142 }143 } catch (NoSuchElementException e) {144 lastException = e;145 // Should use JUnit's AssertionError, but it may not be present146 throw new NoSuchElementError("Unable to locate the element", e);147 }148 }149 public NoSuchElementException getLastException() {150 return lastException;151 }152 public WebElement getElement() {153 return element;154 }155 }156 private class SlowLoadingElementList extends SlowLoadableComponent<SlowLoadingElementList> {157 private NoSuchElementException lastException;158 private List<WebElement> elements;159 public SlowLoadingElementList(Clock clock, int timeOutInSeconds) {160 super(clock, timeOutInSeconds);161 }162 @Override163 protected void load() {164 // Does nothing165 }166 @Override167 protected long sleepFor() {168 return AjaxElementLocator.this.sleepFor();169 }170 @Override171 protected void isLoaded() throws Error {172 try {173 elements = AjaxElementLocator.super.findElements();174 if (elements.size() == 0) {175 throw new NoSuchElementException("Unable to locate the element");176 }177 for (WebElement element : elements) {178 if (!isElementUsable(element)) {179 throw new NoSuchElementException("Element is not usable");180 }181 }182 } catch (NoSuchElementException e) {183 lastException = e;184 // Should use JUnit's AssertionError, but it may not be present185 throw new NoSuchElementError("Unable to locate the element", e);186 }187 }188 public NoSuchElementException getLastException() {189 return lastException;190 }191 public List<WebElement> getElements() {192 return elements;193 }194 }195 private static class NoSuchElementError extends Error {196 private NoSuchElementError(String message, Throwable throwable) {197 super(message, throwable);198 }199 }200}...
Source:AppiumElementLocator.java
1package io.appium.java_client.pagefactory;23import io.appium.java_client.remote.MobileCapabilityType;45import java.lang.reflect.Field;6import java.util.ArrayList;7import java.util.List;8import java.util.concurrent.TimeUnit;910import org.openqa.selenium.By;11import org.openqa.selenium.Capabilities;12import org.openqa.selenium.HasCapabilities;13import org.openqa.selenium.NoSuchElementException;14import org.openqa.selenium.SearchContext;15import org.openqa.selenium.StaleElementReferenceException;16import org.openqa.selenium.TimeoutException;17import org.openqa.selenium.WebDriver;18import org.openqa.selenium.WebElement;19import org.openqa.selenium.internal.WrapsDriver;20import org.openqa.selenium.internal.WrapsElement;21import org.openqa.selenium.remote.CapabilityType;22import org.openqa.selenium.support.pagefactory.ElementLocator;23import org.openqa.selenium.support.ui.FluentWait;2425import com.google.common.base.Function;2627class AppiumElementLocator implements ElementLocator {28 29 // This function waits for not empty element list using all defined by30 private static class WaitingFunction implements31 Function<By, List<WebElement>> {32 private final SearchContext searchContext;3334 private WaitingFunction(SearchContext searchContext) {35 this.searchContext = searchContext;36 }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}
...
Source:HeadLessBrowser.java
1package selenium_concept;2import org.openqa.selenium.SearchContext;3import org.openqa.selenium.TakesScreenshot;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.WebElement;6import org.openqa.selenium.chrome.ChromeDriver;7import org.openqa.selenium.chrome.ChromeOptions;8import org.openqa.selenium.firefox.FirefoxDriver;9import org.openqa.selenium.firefox.FirefoxOptions;10import io.github.bonigarcia.wdm.WebDriverManager;11public class HeadLessBrowser {12 WebElement element;13 14 public static void main(String[] args) {15 16 //headless: No UI17 //testing is happening behind the scene18 //faster than normal UI mode19 /**20 * this is an optional 21 * usually we dont use it 22 * lets say we are expecting some pops or mouse movement 23 * in that case it might not work 24 * specially with complex dom its not recomenned 25 * its recommended with small amount and simple test cases 26 * there is another headless browser PhantomJS but developers of this browser stopped work on that27 * another one GhostDriver28 * 29 * ------------------------------------------------------------------30 * 31 * webdriver interface is extending searchContext super interface 32 * only two abstract methods find element and find elements coming from searchcontext 33 * 34 * WebElement is also interface its extending SearchContex and TakesScreenshot interface35 * remote webdriver is class is implementing webdriver interface36 * whenever we are executing our test cases locally i mean in my laptop i use webdriver driver = new Chrome or any other 37 * driver 38 * but whenever i need to run my test cases on cloud for example on docker or aws on that case i use 39 * webdriver driver = new remote webdriver 40 * remote webdriver has constructor and it says pass a remote url 41 * and some capabilities so that i can execute test cases on the remote machine 42 * 43 * chromeDriver first is extending cromium driver which is another class then extending remotewebdriver is implementing webdriver interface44 * but another browsers like safari opera firefox they are directly extending remote webdriver 45 * 46 */47 48 WebDriverManager.chromedriver().setup();49 ChromeOptions co = new ChromeOptions();50 co.addArguments("--headless");51 WebDriver driver = new ChromeDriver(co);52 53 54 55 56// WebDriverManager.firefoxdriver().setup();57// FirefoxOptions fo = new FirefoxOptions();58// fo.addArguments("--headless");59// 60// WebDriver driver = new FirefoxDriver(fo);61// 62 63 64 driver.get("http://www.google.com");65 System.out.println(driver.getTitle());66 System.out.println(driver.getCurrentUrl());67 68 69 }70}...
Source:Page.java
1package com.seedcompany.cordtables.pages;2import org.openqa.selenium.By;3import org.openqa.selenium.SearchContext;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.WebElement;6import org.slf4j.Logger;7import org.slf4j.LoggerFactory;8import com.seedcompany.cordtables.utils.MenuUtils;9import com.seedcompany.cordtables.utils.SeleniumUtils;10/**11 * Abstract class representation of a Page in the UI. Page object pattern12 */13public abstract class Page {14 private static Logger logger = LoggerFactory.getLogger(Page.class);15 protected WebDriver driver;16 protected SearchContext rootApp;17 public MenuUtils menuUtils;18 public SearchContext getRootApp() {19 return rootApp;20 }21 public void setRootApp(SearchContext rootApp) {22 this.rootApp = rootApp;23 if (menuUtils != null) {24 this.menuUtils.rootApp = rootApp;25 } else {26 this.menuUtils = new MenuUtils(this.rootApp);27 }28 }29 /*30 * Constructor injecting the WebDriver interface31 * 32 * @param webDriver33 */34 public Page(WebDriver driver) {35 this.driver = driver;36 }37 public String getTitle() {38 return driver.getTitle();39 }40 /**41 * Method to load the app.42 * 43 * @return44 */45 public SearchContext loadApp() {46 this.setRootApp(SeleniumUtils.expand_shadow_element(driver.findElement(By.tagName("app-root"))));47 return this.rootApp;48 }49 /**50 * Method to open the menu on home page.51 * 52 * @return53 */54 public SearchContext openMenu() {55 SeleniumUtils.wait(2);56 SearchContext appRoot = loadApp();57 SeleniumUtils.wait(1);58 SearchContext appHeader = SeleniumUtils59 .expand_shadow_element(appRoot.findElement(By.cssSelector("cf-header.hydrated")));60 SearchContext ionIcon = SeleniumUtils61 .expand_shadow_element(appHeader.findElement(By.cssSelector("ion-icon.md")));62 WebElement menu = ionIcon.findElement(By.cssSelector(".ionicon"));63 menu.click();64 SeleniumUtils.wait(1);65 return appHeader;66 }67 /**68 * Method for logout69 */70 public void logout() {71 try {72 SearchContext menuHeader = SeleniumUtils73 .expand_shadow_element(openMenu().findElement(By.cssSelector("cf-header-menu.hydrated")));74 menuHeader.findElement(By.cssSelector("button.menu-item:nth-child(4)")).click();75 SeleniumUtils.wait(1);76 } catch (Exception e) {77 // TODO: handle exception78 }79 }80}...
Source:MyLoginAsInterfacePo.java
1/*2 * Copyright (C) 2013 - 2018 Michael Bulla [michaelbulla@gmail.com]3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 * 8 * http://www.apache.org/licenses/LICENSE-2.09 * 10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 *16 */17package org.popper.migration;1819import org.openqa.selenium.By;20import org.openqa.selenium.SearchContext;21import org.openqa.selenium.WebDriver;22import org.openqa.selenium.WebElement;23import org.popper.fw.element.IButton;24import org.popper.fw.element.ITextBox;25import org.popper.fw.webdriver.annotations.Page;26import org.popper.fw.webdriver.annotations.locator.Locator;2728@Page(name="My Login")29public interface MyLoginAsInterfacePo {30 @Locator(name="Username", id="username")31 ITextBox getUsernameTextbox();3233 @Locator(name="Password", id="password")34 ITextBox getPasswordTextbox();3536 @Locator(name="Submit", id="submit")37 IButton getLoginButton();3839 @Locator(name="Header", id="header")40 Header getHeader();4142 public static class Header {43 protected final WebDriver driver;4445 private SearchContext searchContext;4647 public Header(WebDriver driver, By by) {48 this.driver = driver;49 this.searchContext = driver.findElement(by);50 }5152 public WebElement getIndexLink() {53 return searchContext.findElement(By.xpath("./a[1]"));54 }55 }56}
...
Source:BootstrapModal.java
1package com.caremark.portal.poc.modals;2import org.openqa.selenium.Alert;3import org.openqa.selenium.By;4import org.openqa.selenium.SearchContext;5import org.openqa.selenium.security.Credentials;6public class BootstrapModal implements Alert { // implement alert to ensure the interface is familiar7 private final SearchContext searchContext;8 public BootstrapModal(SearchContext searchContext) { // accept just the part of the page we are interested in9 this.searchContext = searchContext;10 }11 @Override12 public void dismiss() {13 searchContext.findElement(By.cssSelector("button.btn-default")).click(); // the cancel button14 }15 @Override16 public void accept() {17 searchContext.findElement(By.cssSelector("button.btn-primary")).click(); // the ok button18 }19 @Override20 public String getText() {21 return searchContext.findElement(By.cssSelector("h4.modal-title")).getText(); // the input22 }23 @Override24 public void sendKeys(String keysToSend) {25 searchContext.findElement(By.cssSelector("input[type='text']")).sendKeys(keysToSend);26 }27 @Override28 public void setCredentials(Credentials credentials) {29 throw new UnsupportedOperationException();30 }31 @Override32 public void authenticateUsing(Credentials credentials) {33 throw new UnsupportedOperationException();34 }35}...
Source:ByTest.java
1package org.openqa.selenium;2import org.openqa.selenium.internal.FindsById;3import org.openqa.selenium.internal.FindsByLinkText;4import org.openqa.selenium.internal.FindsByName;5import org.openqa.selenium.internal.FindsByXPath;6import org.jmock.Expectations;7import org.jmock.integration.junit3.MockObjectTestCase;8public class ByTest extends MockObjectTestCase {9 public void testShouldUseFindsByNameToLocateElementsByName() {10 final AllDriver driver = mock(AllDriver.class);11 checking(new Expectations() {{12 one(driver).findElementByName("cheese");13 }});14 By by = By.name("cheese");15 by.findElement((SearchContext) driver);16 }17 public void xtestShouldUseXPathToFindByNameIfDriverDoesNotImplementFindsByName() {18 final OnlyXPath driver = mock(OnlyXPath.class);19 checking(new Expectations() {{20 one(driver).findElementByXPath("//*[@name='cheese']");21 }});22 By by = By.name("cheese");23 by.findElement((SearchContext) driver);24 }25 private interface AllDriver extends FindsById, FindsByLinkText, FindsByName, FindsByXPath, SearchContext {26 // Place holder27 }28 private interface OnlyXPath extends FindsByXPath, SearchContext {29 }30}...
Source:WaitMethods.java
1package webui.tests.components.conditions;2import org.openqa.selenium.By;3import org.openqa.selenium.SearchContext;4import org.openqa.selenium.WebElement;5import org.openqa.selenium.support.ui.ExpectedCondition;6import java.util.Collection;7import java.util.concurrent.TimeUnit;8/**9 * Created with IntelliJ IDEA.10 * User: guym11 * Date: 10/8/1312 * Time: 8:53 PM13 */14public interface WaitMethods<T> {15 public T elements( long timeout, TimeUnit unit, final WebElement... webElements );16 public T elements( final WebElement ... webElements );17 // waits until element is not visible18 public T hidden( SearchContext searchContext, By... findBys );19 public T hidden( long timeout, TimeUnit unit, SearchContext searchContext, By... findBys );20 public <V> V predicate( long timeout, TimeUnit unit, ExpectedCondition<V> predicate );21 public <V> V predicate( ExpectedCondition<V> predicate );22 public T size( Collection<WebElement> elements, SizeCondition cond );23}...
Interface SearchContext
Using AI Code Generation
1import org.openqa.selenium.By;2import org.openqa.selenium.SearchContext;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.WebElement;5import org.openqa.selenium.chrome.ChromeDriver;6import org.openqa.selenium.support.ui.ExpectedConditions;7import org.openqa.selenium.support.ui.WebDriverWait;8import java.util.List;9public class CustomSearchContext {10 public static void main(String[] args) {11 System.setProperty("webdriver.chrome.driver","C:\\Users\\navee\\Downloads\\chromedriver_win32\\chromedriver.exe");12 WebDriver driver = new ChromeDriver();13 WebDriverWait wait = new WebDriverWait(driver,10);14 System.out.println(list.size());15 driver.quit();16 }17}
Interface SearchContext
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.ui.Select;6import org.openqa.selenium.support.ui.WebDriverWait;7import org.testng.annotations.AfterTest;8import org.testng.annotations.BeforeTest;9import org.testng.annotations.Test;10public class Test1 {11 WebDriver driver;12 WebDriverWait wait;13 public void setup()14 {15 System.setProperty("webdriver.chrome.driver", "C:\\Users\\vijay\\Downloads\\chromedriver_win32\\chromedriver.exe");16 driver = new ChromeDriver();17 wait = new WebDriverWait(driver, 10);18 }19 public void test1() throws InterruptedException20 {21 WebElement searchbox = driver.findElement(By.name("q"));22 searchbox.sendKeys("Selenium");23 Select sel = new Select(searchbox);24 sel.selectByValue("Selenium");25 Thread.sleep(2000);26 }27 public void teardown()28 {29 driver.quit();30 }31}32BUILD SUCCESSFUL (total time: 3 seconds)
Interface SearchContext
Using AI Code Generation
1List<WebElement> links = driver.findElements(By.tagName("a"));2System.out.println("Number of links on the page are " + links.size());3for(int i=0; i<links.size(); i++) {4System.out.println(links.get(i).getText());5}6driver.quit();7List<WebElement> links = driver.findElements(By.tagName("a"));8System.out.println("Number of links on the page are " + links.size());9for(int i=0; i<links.size(); i++) {10System.out.println(links.get(i).getText());11}12driver.quit();
Interface SearchContext
Using AI Code Generation
1package com.selenium;2import java.util.List;3import org.openqa.selenium.By;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.WebElement;6import org.openqa.selenium.firefox.FirefoxDriver;7import org.openqa.selenium.support.ui.Select;8public class SeleniumInterfaceSearchContext {9public static void main(String[] args) {10WebDriver driver = new FirefoxDriver();11List<WebElement> elements = driver.findElements(By.tagName("input"));12System.out.println("Number of elements:" + elements.size());13for (int i=0; i < elements.size();i++){14System.out.println("Element " + i + " " + elements.get(i).getAttribute("type"));15}16}17}18Selenium Interface SearchContext: findElement(By by) method19public WebElement findElement(By by)20package com.selenium;21import java.util.List;22import org.openqa.selenium.By;23import org.openqa.selenium.WebDriver;24import org.openqa.selenium.WebElement;25import org.openqa.selenium.firefox.FirefoxDriver;26import org.openqa.selenium.support.ui.Select;27public class SeleniumInterfaceSearchContext {28public static void main(String[] args) {29WebDriver driver = new FirefoxDriver();30WebElement element = driver.findElement(By.id("email"));31System.out.println("Element is:" + element.getAttribute("id"));32}33}34Selenium Interface SearchContext: findElements(By by) method35The findElements(By by) method of Interface SearchContext is used to find all elements matching the given criteria. It returns an empty list if no matching elements are found. It takes
Interface SearchContext
Using AI Code Generation
1public class SearchContextExample {2 public static void main(String[] args) {3 WebDriver driver = new FirefoxDriver();4 SearchContext searchContext = (SearchContext) driver;5 WebElement searchBox = searchContext.findElement(By.name("q"));6 searchBox.sendKeys("selenium");7 searchBox.submit();8 }9}10public class TakesScreenshotExample {11 public static void main(String[] args) throws IOException {12 WebDriver driver = new FirefoxDriver();13 File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);14 FileUtils.copyFile(srcFile, new File("c:\\screenshot.png"));15 }16}17public class WebDriverExample {18 public static void main(String[] args) {19 WebDriver driver = new FirefoxDriver();20 }21}22public class WebDriverNavigationExample {23 public static void main(String[] args) {24 WebDriver driver = new FirefoxDriver();25 Navigation navigation = driver.navigate();26 navigation.back();27 navigation.forward();28 navigation.refresh();29 }30}31public class WebDriverOptionsExample {32 public static void main(String[] args) {33 WebDriver driver = new FirefoxDriver();34 Options options = driver.manage();35 options.addCookie(new Cookie("key", "value"));36 Set<Cookie> cookies = options.getCookies();37 for(Cookie cookie : cookies) {38 System.out.println(cookie.getName() + " : " + cookie.getValue());39 }40 options.deleteAllCookies();41 }42}43public class WebDriverTargetLocatorExample {44 public static void main(String[] args) {45 WebDriver driver = new FirefoxDriver();46 TargetLocator targetLocator = driver.switchTo();47 targetLocator.activeElement();48 targetLocator.defaultContent();49 targetLocator.frame(
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!!