Best Selenium code snippet using org.openqa.selenium.Interface WebDriver
Source:BaseAugmenter.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.remote;18import static org.openqa.selenium.remote.CapabilityType.HAS_TOUCHSCREEN;19import static org.openqa.selenium.remote.CapabilityType.ROTATABLE;20import static org.openqa.selenium.remote.CapabilityType.SUPPORTS_APPLICATION_CACHE;21import static org.openqa.selenium.remote.CapabilityType.SUPPORTS_FINDING_BY_CSS;22import static org.openqa.selenium.remote.CapabilityType.SUPPORTS_LOCATION_CONTEXT;23import static org.openqa.selenium.remote.CapabilityType.SUPPORTS_NETWORK_CONNECTION;24import static org.openqa.selenium.remote.CapabilityType.SUPPORTS_WEB_STORAGE;25import org.openqa.selenium.WebDriver;26import org.openqa.selenium.WebElement;27import org.openqa.selenium.remote.html5.AddApplicationCache;28import org.openqa.selenium.remote.html5.AddLocationContext;29import org.openqa.selenium.remote.html5.AddWebStorage;30import org.openqa.selenium.remote.mobile.AddNetworkConnection;31import java.util.HashMap;32import java.util.Map;33/**34 * Enhance the interfaces implemented by an instance of the35 * {@link org.openqa.selenium.remote.RemoteWebDriver} based on the returned36 * {@link org.openqa.selenium.Capabilities} of the driver.37 *38 * Note: this class is still experimental. Use at your own risk.39 */40public abstract class BaseAugmenter {41 private final Map<String, AugmenterProvider> driverAugmentors = new HashMap<>();42 private final Map<String, AugmenterProvider> elementAugmentors = new HashMap<>();43 public BaseAugmenter() {44 addDriverAugmentation(SUPPORTS_FINDING_BY_CSS, new AddFindsByCss());45 addDriverAugmentation(SUPPORTS_LOCATION_CONTEXT, new AddLocationContext());46 addDriverAugmentation(SUPPORTS_APPLICATION_CACHE, new AddApplicationCache());47 addDriverAugmentation(SUPPORTS_NETWORK_CONNECTION, new AddNetworkConnection());48 addDriverAugmentation(SUPPORTS_WEB_STORAGE, new AddWebStorage());49 addDriverAugmentation(ROTATABLE, new AddRotatable());50 addDriverAugmentation(HAS_TOUCHSCREEN, new AddRemoteTouchScreen());51 addElementAugmentation(SUPPORTS_FINDING_BY_CSS, new AddFindsChildByCss());52 }53 /**54 * Add a mapping between a capability name and the implementation of the interface that name55 * represents for instances of {@link org.openqa.selenium.WebDriver}. For example (@link56 * CapabilityType#SUPPORTS_FINDING_BY_CSS} represents the interface57 * {@link org.openqa.selenium.internal.FindsByCssSelector}, which is implemented via the58 * {@link org.openqa.selenium.remote.AddFindsByCss} provider.59 *60 * Note: This method is still experimental. Use at your own risk.61 *62 * @param capabilityName The name of the capability to model63 * @param handlerClass The provider of the interface and implementation64 */65 public void addDriverAugmentation(String capabilityName, AugmenterProvider handlerClass) {66 driverAugmentors.put(capabilityName, handlerClass);67 }68 /**69 * Add a mapping between a capability name and the implementation of the interface that name70 * represents for instances of {@link org.openqa.selenium.WebElement}. For example (@link71 * CapabilityType#SUPPORTS_FINDING_BY_CSS} represents the interface72 * {@link org.openqa.selenium.internal.FindsByCssSelector}, which is implemented via the73 * {@link AddFindsByCss} provider.74 *75 * Note: This method is still experimental. Use at your own risk.76 *77 * @param capabilityName The name of the capability to model78 * @param handlerClass The provider of the interface and implementation79 */80 public void addElementAugmentation(String capabilityName, AugmenterProvider handlerClass) {81 elementAugmentors.put(capabilityName, handlerClass);82 }83 /**84 * Enhance the interfaces implemented by this instance of WebDriver iff that instance is a85 * {@link org.openqa.selenium.remote.RemoteWebDriver}.86 *87 * The WebDriver that is returned may well be a dynamic proxy. You cannot rely on the concrete88 * implementing class to remain constant.89 *90 * @param driver The driver to enhance91 * @return A class implementing the described interfaces.92 */93 public WebDriver augment(WebDriver driver) {94 RemoteWebDriver remoteDriver = extractRemoteWebDriver(driver);95 if (remoteDriver == null) {96 return driver;97 }98 return create(remoteDriver, driverAugmentors, driver);99 }100 /**101 * Enhance the interfaces implemented by this instance of WebElement iff that instance is a102 * {@link org.openqa.selenium.remote.RemoteWebElement}.103 *104 * The WebElement that is returned may well be a dynamic proxy. You cannot rely on the concrete105 * implementing class to remain constant.106 *107 * @param element The driver to enhance.108 * @return A class implementing the described interfaces.109 */110 public WebElement augment(RemoteWebElement element) {111 // TODO(simon): We should really add a "SelfDescribing" interface for this112 RemoteWebDriver parent = (RemoteWebDriver) element.getWrappedDriver();113 if (parent == null) {114 return element;115 }116 return create(parent, elementAugmentors, element);117 }118 /**119 * Subclasses should perform the requested augmentation.120 *121 * @param <X> typically a RemoteWebDriver or RemoteWebElement122 * @param augmentors augumentors to augment the object123 * @param driver RWD instance124 * @param objectToAugment object to augment125 * @return an augmented version of objectToAugment.126 */127 protected abstract <X> X create(RemoteWebDriver driver, Map<String, AugmenterProvider> augmentors,128 X objectToAugment);129 /**130 * Subclasses should extract the remote webdriver or return null if it can't extract it.131 *132 * @param driver WebDriver instance to extract133 * @return extracted RemoteWebDriver or null134 */135 protected abstract RemoteWebDriver extractRemoteWebDriver(WebDriver driver);136}...
Source:EventListener.java
1/*2 * 3 */4package com.mifos.testing.framework.webdriver;5import org.apache.commons.io.FileUtils;6import org.openqa.selenium.*;7import org.openqa.selenium.support.events.WebDriverEventListener;8import java.io.File;9import java.io.IOException;10// TODO: Auto-generated Javadoc11/**12 * The listener interface for receiving event events. The class that is13 * interested in processing a event event implements this interface, and the14 * object created with that class is registered with a component using the15 * component's <code>addEventListener<code> method. When16 * the event event occurs, that object's appropriate17 * method is invoked.18 * 19 * @see EventEvent20 */21public class EventListener implements WebDriverEventListener {22 // @Override23 // public void onException(java.lang.Throwable throwable, WebDriver driver)24 // {25 //26 // WebDriver augmentedDriver = new Augmenter().augment(driver);27 // File source =28 // ((TakesScreenshot)augmentedDriver).getScreenshotAs(OutputType.FILE);29 //30 // String path = "./target/screenshots/";31 //32 // if (!(System.getProperty("screenshot.folder").equals(null)) ){33 // path = System.getProperty("screenshot.folder");34 // }35 //36 // path = path + source.getName();37 //38 // try {39 // FileUtils.copyFile(source, new File(path));40 // } catch (IOException e) {41 // // TODO Auto-generated catch block42 // e.printStackTrace();43 // }44 //45 // }46 /*47 * (non-Javadoc)48 * 49 * @see50 * org.openqa.selenium.support.events.WebDriverEventListener#afterChangeValueOf51 * (org.openqa.selenium.WebElement, org.openqa.selenium.WebDriver)52 */53 @Override54 public void afterChangeValueOf(WebElement arg0, WebDriver arg1) {55 // TODO Auto-generated method stub56 }57 /*58 * (non-Javadoc)59 * 60 * @see61 * org.openqa.selenium.support.events.WebDriverEventListener#afterClickOn62 * (org.openqa.selenium.WebElement, org.openqa.selenium.WebDriver)63 */64 @Override65 public void afterClickOn(WebElement arg0, WebDriver arg1) {66 // TODO Auto-generated method stub67 }68 /*69 * (non-Javadoc)70 * 71 * @see72 * org.openqa.selenium.support.events.WebDriverEventListener#afterFindBy73 * (org.openqa.selenium.By, org.openqa.selenium.WebElement,74 * org.openqa.selenium.WebDriver)75 */76 @Override77 public void afterFindBy(By arg0, WebElement arg1, WebDriver arg2) {78 arg1.sendKeys(Keys.ARROW_DOWN);79 }80 /*81 * (non-Javadoc)82 * 83 * @see84 * org.openqa.selenium.support.events.WebDriverEventListener#afterNavigateBack85 * (org.openqa.selenium.WebDriver)86 */87 @Override88 public void afterNavigateBack(WebDriver arg0) {89 // TODO Auto-generated method stub90 }91 /*92 * (non-Javadoc)93 * 94 * @see org.openqa.selenium.support.events.WebDriverEventListener#95 * afterNavigateForward(org.openqa.selenium.WebDriver)96 */97 @Override98 public void afterNavigateForward(WebDriver arg0) {99 // TODO Auto-generated method stub100 }101 /*102 * (non-Javadoc)103 * 104 * @see105 * org.openqa.selenium.support.events.WebDriverEventListener#afterNavigateTo106 * (java.lang.String, org.openqa.selenium.WebDriver)107 */108 @Override109 public void afterNavigateTo(String arg0, WebDriver arg1) {110 // TODO Auto-generated method stub111 }112 /*113 * (non-Javadoc)114 * 115 * @see116 * org.openqa.selenium.support.events.WebDriverEventListener#afterScript117 * (java.lang.String, org.openqa.selenium.WebDriver)118 */119 @Override120 public void afterScript(String arg0, WebDriver arg1) {121 // TODO Auto-generated method stub122 }123 /*124 * (non-Javadoc)125 * 126 * @see127 * org.openqa.selenium.support.events.WebDriverEventListener#beforeChangeValueOf128 * (org.openqa.selenium.WebElement, org.openqa.selenium.WebDriver)129 */130 @Override131 public void beforeChangeValueOf(WebElement arg0, WebDriver arg1) {132 // TODO Auto-generated method stub133 }134 /*135 * (non-Javadoc)136 * 137 * @see138 * org.openqa.selenium.support.events.WebDriverEventListener#beforeClickOn139 * (org.openqa.selenium.WebElement, org.openqa.selenium.WebDriver)140 */141 @Override142 public void beforeClickOn(WebElement arg0, WebDriver arg1) {143 // TODO Auto-generated method stub144 }145 /*146 * (non-Javadoc)147 * 148 * @see149 * org.openqa.selenium.support.events.WebDriverEventListener#beforeFindBy150 * (org.openqa.selenium.By, org.openqa.selenium.WebElement,151 * org.openqa.selenium.WebDriver)152 */153 @Override154 public void beforeFindBy(By arg0, WebElement arg1, WebDriver arg2) {155 // TODO Auto-generated method stub156 }157 /*158 * (non-Javadoc)159 * 160 * @see161 * org.openqa.selenium.support.events.WebDriverEventListener#beforeNavigateBack162 * (org.openqa.selenium.WebDriver)163 */164 @Override165 public void beforeNavigateBack(WebDriver arg0) {166 // TODO Auto-generated method stub167 }168 /*169 * (non-Javadoc)170 * 171 * @see org.openqa.selenium.support.events.WebDriverEventListener#172 * beforeNavigateForward(org.openqa.selenium.WebDriver)173 */174 @Override175 public void beforeNavigateForward(WebDriver arg0) {176 // TODO Auto-generated method stub177 }178 /*179 * (non-Javadoc)180 * 181 * @see182 * org.openqa.selenium.support.events.WebDriverEventListener#beforeNavigateTo183 * (java.lang.String, org.openqa.selenium.WebDriver)184 */185 @Override186 public void beforeNavigateTo(String arg0, WebDriver arg1) {187 // TODO Auto-generated method stub188 }189 /*190 * (non-Javadoc)191 * 192 * @see193 * org.openqa.selenium.support.events.WebDriverEventListener#beforeScript194 * (java.lang.String, org.openqa.selenium.WebDriver)195 */196 @Override197 public void beforeScript(String arg0, WebDriver arg1) {198 // TODO Auto-generated method stub199 }200 /*201 * (non-Javadoc)202 * 203 * @see204 * org.openqa.selenium.support.events.WebDriverEventListener#onException205 * (java.lang.Throwable, org.openqa.selenium.WebDriver)206 */207 @Override208 public void onException(Throwable e, WebDriver driver) {209 File source = ((TakesScreenshot) driver)210 .getScreenshotAs(OutputType.FILE);211 String path = "./target/screenshots/";212 // if (!(System.getProperty("screenshot.folder").equals(null)) ){213 // path = System.getProperty("screenshot.folder");214 // }215 path = path + source.getName();216 try {217 FileUtils.copyFile(source, new File(path));218 } catch (IOException e2) {219 // TODO Auto-generated catch block220 e.printStackTrace();221 }222 System.setProperty("screenshottaken", "true");223 }224}...
Source:ExplicitFluentWait.java
1package t1;2import java.time.Duration;3import java.util.ArrayList;4import java.util.List;5import java.util.concurrent.TimeUnit;6import java.util.function.Function;7import org.openqa.selenium.By;8import org.openqa.selenium.Keys;9import org.openqa.selenium.NoSuchElementException;10import org.openqa.selenium.WebDriver;11import org.openqa.selenium.WebElement;12import org.openqa.selenium.chrome.ChromeDriver;13import org.openqa.selenium.support.ui.ExpectedConditions;14import org.openqa.selenium.support.ui.FluentWait;15import org.openqa.selenium.support.ui.Wait;16import org.openqa.selenium.support.ui.WebDriverWait;17public class ExplicitFluentWait {18 public static void main(String[] args) throws InterruptedException {19 System.setProperty("webdriver.chrome.driver", ".//lib//chromedriver.exe");20 WebDriver driver = new ChromeDriver();21 22 // manage is method webdriver In manage there is method timeouts23 // timeouts method return Timeouts in this interface method24 // implicitlyWait(long integer, TimeUnit);25 /*26 * An implementation of the Wait interface that may have its timeout and polling27 * interval configured on the fly. Each FluentWait instance defines the maximum28 * amount of time to wait for a condition, as well as the frequency with which29 * to check the condition. Furthermore, the user may configure the wait to30 * ignore specific types of exceptions whilst waiting, such as31 * NoSuchElementExceptions when searching for an element on the page.32 */33driver.get("https://www.flipkart.com/search?q=Selenium+book&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=on&as=off&page=1");34 35 int count=1;36 while (isVisible(driver,By.xpath("//*[text()='Next']"))) {37 if (isVisible(driver,By.xpath("//*[@class='_4rR01T']"))) {38 List<WebElement> list = driver.findElements(By.xpath("//*[@class='_4rR01T']"));39 for (WebElement ele : list) {40 if (isVisible(driver, By.xpath("//*[@class='_4rR01T']"))) {41 for(int i=0;i<10;i++) {42 System.out.println(count+":"+ele.getText());43 count++;44 break;45 46 }47 }48 }49 }50 Thread.sleep(5000);51 driver.findElement(By.xpath("//*[text()='Next']")).click();52 Thread.sleep(5000);53 }54 55 56 }57 public static boolean isVisible(WebDriver driver, By by) {58 Wait<WebDriver> ft = new FluentWait<WebDriver>(driver).withTimeout(Duration.ofSeconds(60))59 .pollingEvery(Duration.ofSeconds(60)).ignoring(NoSuchElementException.class);60 WebElement ele = ft.until(new Function<WebDriver, WebElement>() {61 @Override62 public WebElement apply(WebDriver driver) {63 return driver.findElement(by);64 }65 });66 return ele.isDisplayed();67 }68}69/*70//Demo 2 Working properly71 72 73import java.time.Duration;74import java.util.concurrent.TimeUnit;75import org.openqa.selenium.By;76import org.openqa.selenium.NoSuchElementException;77import org.openqa.selenium.WebDriver;78import org.openqa.selenium.WebElement;79import org.openqa.selenium.firefox.FirefoxDriver;80import org.openqa.selenium.support.ui.FluentWait; //FluentWait is a Class and it is a part of this package81 82import com.google.common.base.Function;83 84public class ExplicitFluentWait {85 public static void main(String[] args) {86 fluentWaitMethod();87 }88 public static void fluentWaitMethod(){89 System.setProperty("webdriver.gecko.driver",".//lib//geckodriver.exe");90 WebDriver driver = new FirefoxDriver();91 driver.get("http://softwaretestingplace.blogspot.com/2017/02/selenium-fluent-wait.html");92 driver.findElement(By.xpath("//*[@id='post-body-5280210221385817166']/div[1]/button")).click();93 94 95 FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver)96 .withTimeout(Duration.ofSeconds(30))97 .pollingEvery(Duration.ofSeconds(5))98 .ignoring(NoSuchElementException.class);99 100 WebElement element = wait.until(new Function<WebDriver, WebElement>() {101 public WebElement apply(WebDriver driver) {102 WebElement element = driver.findElement(By.xpath("//*[@id=\"myAnchor\"]"));103 String getTextOnPage = element.getText();104 System.out.println(getTextOnPage);105 if(getTextOnPage.equals("www.SoftwareTestingMaterial.com")){106 System.out.println(getTextOnPage);107 return element;108 }else{109 System.out.println("FluentWait Failed");110 return null;111 }112 }113 });114 }115}*/...
Source:Utils.java
1package org.openqa.selenium.remote.server.handler.html5;2import com.google.common.base.Throwables;3import java.lang.reflect.Constructor;4import java.lang.reflect.InvocationTargetException;5import org.openqa.selenium.Capabilities;6import org.openqa.selenium.HasCapabilities;7import org.openqa.selenium.UnsupportedCommandException;8import org.openqa.selenium.WebDriver;9import org.openqa.selenium.WebDriverException;10import org.openqa.selenium.html5.ApplicationCache;11import org.openqa.selenium.html5.LocationContext;12import org.openqa.selenium.html5.WebStorage;13import org.openqa.selenium.mobile.NetworkConnection;14import org.openqa.selenium.remote.ExecuteMethod;15import org.openqa.selenium.remote.html5.RemoteApplicationCache;16import org.openqa.selenium.remote.html5.RemoteLocationContext;17import org.openqa.selenium.remote.html5.RemoteWebStorage;18import org.openqa.selenium.remote.mobile.RemoteNetworkConnection;19public class Utils20{21 public Utils() {}22 23 static ApplicationCache getApplicationCache(WebDriver driver)24 {25 return (ApplicationCache)convert(driver, ApplicationCache.class, "applicationCacheEnabled", RemoteApplicationCache.class);26 }27 28 public static NetworkConnection getNetworkConnection(WebDriver driver)29 {30 return (NetworkConnection)convert(driver, NetworkConnection.class, "networkConnectionEnabled", RemoteNetworkConnection.class);31 }32 33 static LocationContext getLocationContext(WebDriver driver)34 {35 return (LocationContext)convert(driver, LocationContext.class, "locationContextEnabled", RemoteLocationContext.class);36 }37 38 static WebStorage getWebStorage(WebDriver driver)39 {40 return (WebStorage)convert(driver, WebStorage.class, "webStorageEnabled", RemoteWebStorage.class);41 }42 43 private static <T> T convert(WebDriver driver, Class<T> interfaceClazz, String capability, Class<? extends T> remoteImplementationClazz)44 {45 if (interfaceClazz.isInstance(driver)) {46 return interfaceClazz.cast(driver);47 }48 49 if (((driver instanceof ExecuteMethod)) && ((driver instanceof HasCapabilities)))50 {51 if (((HasCapabilities)driver).getCapabilities().is(capability)) {52 try {53 return 54 55 remoteImplementationClazz.getConstructor(new Class[] { ExecuteMethod.class }).newInstance(new Object[] { (ExecuteMethod)driver });56 } catch (InstantiationException e) {57 throw new WebDriverException(e);58 } catch (IllegalAccessException e) {59 throw new WebDriverException(e);60 } catch (InvocationTargetException e) {61 throw Throwables.propagate(e.getCause());62 } catch (NoSuchMethodException e) {63 throw new WebDriverException(e);64 }65 }66 }67 68 throw new UnsupportedCommandException("driver (" + driver.getClass().getName() + ") does not support " + interfaceClazz.getName());69 }70}...
Source:WebdriverTest.java
1package configFiles;2import org.openqa.selenium.*;3import org.openqa.selenium.logging.Logs;4import java.net.URL;5import java.util.List;6import java.util.Set;7import java.util.concurrent.TimeUnit;8import java.net.URL;9import java.util.List;10import java.util.Set;11import java.util.concurrent.TimeUnit;12import org.openqa.selenium.logging.Logs;13public interface WebdriverTest{14 public interface WebDriver extends SearchContext {15 void get(String var1);16 String getCurrentUrl();17 String getTitle();18 List<WebElement> findElements(By var1);19 WebElement findElement(By var1);20 String getPageSource();21 void close();22 void quit();23 Set<String> getWindowHandles();24 String getWindowHandle();25 org.openqa.selenium.WebDriver.TargetLocator switchTo();26 org.openqa.selenium.WebDriver.Navigation navigate();27 org.openqa.selenium.WebDriver.Options manage();28 @Beta29 public interface Window {30 void setSize(Dimension var1);31 void setPosition(Point var1);32 Dimension getSize();33 Point getPosition();34 void maximize();35 }36 public interface ImeHandler {37 List<String> getAvailableEngines();38 String getActiveEngine();39 boolean isActivated();40 void deactivate();41 void activateEngine(String var1);42 }43 public interface Navigation {44 void back();45 void forward();46 void to(String var1);47 void to(URL var1);48 void refresh();49 }50 public interface TargetLocator {51 org.openqa.selenium.WebDriver frame(int var1);52 org.openqa.selenium.WebDriver frame(String var1);53 org.openqa.selenium.WebDriver frame(WebElement var1);54 org.openqa.selenium.WebDriver window(String var1);55 org.openqa.selenium.WebDriver defaultContent();56 WebElement activeElement();57 Alert alert();58 }59 public interface Timeouts {60 org.openqa.selenium.WebDriver.Timeouts implicitlyWait(long var1, TimeUnit var3);61 org.openqa.selenium.WebDriver.Timeouts setScriptTimeout(long var1, TimeUnit var3);62 }63 public interface Options {64 void addCookie(Cookie var1);65 void deleteCookieNamed(String var1);66 void deleteCookie(Cookie var1);67 void deleteAllCookies();68 Set<Cookie> getCookies();69 Cookie getCookieNamed(String var1);70 org.openqa.selenium.WebDriver.Timeouts timeouts();71 org.openqa.selenium.WebDriver.ImeHandler ime();72 @Beta73 org.openqa.selenium.WebDriver.Window window();74 @Beta75 Logs logs();76 }77 }78}...
Source:WebEventListener.java
1package com.edu.Utilities;2import org.openqa.selenium.WebDriver;3import org.openqa.selenium.WebElement;4import org.openqa.selenium.support.events.AbstractWebDriverEventListener;5import org.testng.Reporter;6// TODO: Auto-generated Javadoc7/**8 * The listener interface for receiving webEvent events.9 * The class that is interested in processing a webEvent10 * event implements this interface, and the object created11 * with that class is registered with a component using the12 * component's <code>addWebEventListener<code> method. When13 * the webEvent event occurs, that object's appropriate14 * method is invoked.15 *16 * @see WebEventEvent17 */18public class WebEventListener extends AbstractWebDriverEventListener {19 20 /* (non-Javadoc)21 * @see org.openqa.selenium.support.events.AbstractWebDriverEventListener#beforeNavigateTo(java.lang.String, org.openqa.selenium.WebDriver)22 */23 public void beforeNavigateTo(String url, WebDriver driver) {24 System.out.println("Before navigating to: '" + url + "'");25 }26 /* (non-Javadoc)27 * @see org.openqa.selenium.support.events.AbstractWebDriverEventListener#afterNavigateTo(java.lang.String, org.openqa.selenium.WebDriver)28 */29 public void afterNavigateTo(String url, WebDriver driver) {30 //System.out.println("Navigated to:'" + url + "'");31 }32 /* (non-Javadoc)33 * @see org.openqa.selenium.support.events.AbstractWebDriverEventListener#beforeClickOn(org.openqa.selenium.WebElement, org.openqa.selenium.WebDriver)34 */35 public void beforeClickOn(WebElement element, WebDriver driver) {36 String elementText = element.getText();37 try {38 if (!elementText.isEmpty()) {39 if (elementText.length() < 100) {40 System.out.println("Clicked on: " + element.getText());41 Reporter.log("Clicked on: " + element.getText());42 }43 }44 } catch (Exception e) {45 elementText = element.getAttribute("textcontent");46 try {47 if (!elementText.isEmpty()) {48 if (elementText.length() < 100) {49 System.out.println("Clicked on: " + element.getAttribute("textcontent"));50 Reporter.log("Clicked on: " + element.getAttribute("textcontent"));51 }52 }53 } catch (Exception ex) {54 System.out.println("Clicked on: " + element.toString());55 Reporter.log("Clicked on: " + element.toString());56 }57 }58 }59 /* (non-Javadoc)60 * @see org.openqa.selenium.support.events.AbstractWebDriverEventListener#afterClickOn(org.openqa.selenium.WebElement, org.openqa.selenium.WebDriver)61 */62 public void afterClickOn(WebElement element, WebDriver driver) {63 }64 /* (non-Javadoc)65 * @see org.openqa.selenium.support.events.AbstractWebDriverEventListener#onException(java.lang.Throwable, org.openqa.selenium.WebDriver)66 */67 public void onException(Throwable error, WebDriver driver) {68 }69}...
Source:WebDrivers.java
1package seleniumjavatpoint;2import org.openqa.selenium.By;3import org.openqa.selenium.Keys;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.WebElement;6import org.openqa.selenium.chrome.ChromeDriver;7import org.openqa.selenium.firefox.FirefoxDriver;8import org.openqa.selenium.ie.InternetExplorerDriver;9import org.openqa.selenium.remote.DesiredCapabilities;10import org.openqa.selenium.safari.SafariDriver;11import org.openqa.selenium.support.ui.ExpectedConditions;12import org.openqa.selenium.support.ui.Wait;13import org.openqa.selenium.support.ui.WebDriverWait;14public class WebDrivers {15 public static void main(String[] args) {16 firefoxDriver();17 chromeDriver();18 }19 public static void chromeDriver(){20 //Creating a driver object referencing WebDriver interface21 WebDriver driver;22//Setting the webdriver.chrome.driver property to its executable's location23 System.setProperty("webdriver.chrome.driver", "/Library/chromedriver");24//Instantiating driver object25 driver = new ChromeDriver();26//Using get() method to open a webpage27 driver.get("http://javatpoint.com");28//Closing the browser29 driver.quit();30 }31 public static void ieDriver(){32 //Creating a driver object referencing WebDriver interface33 WebDriver driver;34//Setting the webdriver.ie.driver property to its executable's location35 System.setProperty("webdriver.ie.driver", "/lib/IEDriverServer/IEDriverServer.exe");36//Instantiating driver object37 driver = new InternetExplorerDriver();38//Using get() method to open a webpage39 driver.get("http://javatpoint.com");40//Closing the browser41 driver.quit();42 }43 public static void firefoxDriver() {44 // System Property for Gecko Driver45 System.setProperty("webdriver.gecko.driver", System.getProperty("user.dir")+"/resources/webdrivers/mac/geckodriver");46 // Initialize Gecko Driver using Desired Capabilities Class47 DesiredCapabilities capabilities = DesiredCapabilities.firefox();48 capabilities.setCapability("marionette",true);49 WebDriver driver= new FirefoxDriver(capabilities);50 // Launch Website51 driver.navigate().to("http://www.javatpoint.com/");52 //Closing the browser53 driver.quit();54 }55}...
Source:FluentWaitTest.java
1package com.fiserv.advance;2import java.time.Duration;3import java.util.NoSuchElementException;4import java.util.concurrent.TimeUnit;5import java.util.function.Function;6import org.openqa.selenium.Alert;7import org.openqa.selenium.By;8import org.openqa.selenium.NoAlertPresentException;9import org.openqa.selenium.NoSuchWindowException;10import org.openqa.selenium.StaleElementReferenceException;11import org.openqa.selenium.WebDriver;12import org.openqa.selenium.WebElement;13import org.openqa.selenium.chrome.ChromeDriver;14import org.openqa.selenium.support.ui.ExpectedConditions;15import org.openqa.selenium.support.ui.FluentWait;16public class FluentWaitTest {17 public static void main(String[] args) {18 WebDriver driver = new ChromeDriver();19 driver.manage().window().maximize();20 // driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);21 driver.get("https://demo.openemr.io/b/openemr/interface/login/login.php?site=default");22 // nosuchwind23 // driver.findElement(By.id("user")).sendKeys("hello");24 FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(Duration.ofSeconds(40))25 .pollingEvery(Duration.ofSeconds(1)).ignoring(Exception.class);26 Alert alert = wait.until(new Function<WebDriver, Alert>() {27 @Override28 public Alert apply(WebDriver t) {29 // TODO Auto-generated method stub30 return t.switchTo().alert();31 }32 });33 34 System.out.println(alert.getText());35 36 WebElement ele = wait.until(new Function<WebDriver, WebElement>() {37 @Override38 public WebElement apply(WebDriver driver) {39 // TODO Auto-generated method stub40 return driver.findElement(By.id("authUser"));41 }42 });43 44 ele.sendKeys("hello");45 }46}...
Interface WebDriver
Using AI Code Generation
1package selenium;2import org.openqa.selenium.By;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.WebElement;5import org.openqa.selenium.chrome.ChromeDriver;6public class FirstSelenium {7 public static void main(String[] args) {8 System.setProperty("webdriver.chrome.driver", "C:\\Users\\Saurabh\\Downloads\\chromedriver_win32\\chromedriver.exe");9 WebDriver driver = new ChromeDriver();10 WebElement element = driver.findElement(By.name("q"));11 element.sendKeys("Selenium");12 element.submit();13 System.out.println(driver.getTitle());14 driver.quit();15 }16}17Selenium is a suite of tools to automate web browsers across many platforms. Selenium provides a playback tool for authoring tests without the need to learn a test scripting language (Selenium IDE). It also provides a test domain-specific language (Selenese) to write tests in a number of popular programming
Interface WebDriver
Using AI Code Generation
1import org.openqa.selenium.WebDriver;2import org.openqa.selenium.chrome.ChromeDriver;3public class TestSelenium {4public static void main(String[] args) {5 System.setProperty("webdriver.chrome.driver", "C:\\Users\\Admin\\Downloads\\chromedriver_win32\\chromedriver.exe");6 WebDriver driver = new ChromeDriver();7 driver.quit();8}9}10import org.openqa.selenium.WebDriver;11import org.openqa.selenium.chrome.ChromeDriver;12import org.openqa.selenium.remote.RemoteWebDriver;13public class TestSelenium {14public static void main(String[] args) {15 System.setProperty("webdriver.chrome.driver", "C:\\Users\\Admin\\Downloads\\chromedriver_win32\\chromedriver.exe");16 RemoteWebDriver driver = new ChromeDriver();17 driver.quit();18}19}20import org.openqa.selenium.JavascriptExecutor;21import org.openqa.selenium.WebDriver;22import org.openqa.selenium.chrome.ChromeDriver;23public class TestSelenium {24public static void main(String[] args) {25 System.setProperty("webdriver.chrome.driver", "C:\\Users\\Admin\\Downloads\\chromedriver_win32\\chromedriver.exe");26 WebDriver driver = new ChromeDriver();27 JavascriptExecutor js = (JavascriptExecutor)driver;28 js.executeScript("alert('Hello World');");29 driver.quit();30}31}32import org.openqa.selenium.OutputType;33import org.openqa.selenium.TakesScreenshot;34import org.openqa.selenium.WebDriver;35import org.openqa.selenium.chrome.ChromeDriver;36public class TestSelenium {37public static void main(String[] args) {38 System.setProperty("webdriver.chrome.driver", "C:\\Users\\Admin\\Downloads\\chromedriver_win32\\chromedriver.exe");39 WebDriver driver = new ChromeDriver();40 TakesScreenshot ts = (TakesScreenshot)driver;41 File source = ts.getScreenshotAs(OutputType.FILE);42 FileUtils.copyFile(source, new File("./Screenshots/google.png"));43 System.out.println("The Screenshot is taken");44 driver.quit();45}46}47import org.openqa.selenium.Keys;48import org.openqa.selenium.WebDriver;49import org.openqa.selenium.chrome.ChromeDriver;50import org.openqa.selenium.interactions.Actions;51public class TestSelenium {
Interface WebDriver
Using AI Code Generation
1import org.openqa.selenium.WebDriver;2import org.openqa.selenium.chrome.ChromeDriver;3public class FirstSeleniumScript {4 public static void main(String[] args) {5 System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\chromedriver.exe");6 WebDriver driver = new ChromeDriver();7 driver.close();8 }9}
Interface WebDriver
Using AI Code Generation
1import org.openqa.selenium.WebDriver;2import org.openqa.selenium.chrome.ChromeDriver;3public class SeleniumWebDriverDemo {4 public static void main(String[] args) {5 WebDriver driver = new ChromeDriver();6 driver.manage().window().maximize();7 String title = driver.getTitle();8 System.out.println(title);9 String url = driver.getCurrentUrl();10 System.out.println(url);11 String sourceCode = driver.getPageSource();12 System.out.println(sourceCode);13 driver.close();14 }15}16import org.openqa.selenium.WebDriver;17import org.openqa.selenium.chrome.ChromeDriver;18public class SeleniumWebDriverDemo {19 public static void main(String[] args) {20 WebDriver driver = new ChromeDriver();21 driver.manage().window().maximize();22 String title = driver.getTitle();23 System.out.println(title);24 String url = driver.getCurrentUrl();
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!!