Best Selenium code snippet using org.openqa.selenium.Interface WebDriver.findElement
Source:WebDriverEventListener.java
...101 * @param driver WebDriver102 */103 void afterNavigateRefresh(WebDriver driver);104 /**105 * Called before {@link WebDriver#findElement WebDriver.findElement(...)}, or106 * {@link WebDriver#findElements WebDriver.findElements(...)}, or {@link WebElement#findElement107 * WebElement.findElement(...)}, or {@link WebElement#findElement WebElement.findElements(...)}.108 *109 * @param element will be <code>null</code>, if a find method of <code>WebDriver</code> is called.110 * @param by locator being used111 * @param driver WebDriver112 */113 void beforeFindBy(By by, WebElement element, WebDriver driver);114 /**115 * Called after {@link WebDriver#findElement WebDriver.findElement(...)}, or116 * {@link WebDriver#findElements WebDriver.findElements(...)}, or {@link WebElement#findElement117 * WebElement.findElement(...)}, or {@link WebElement#findElement WebElement.findElements(...)}.118 *119 * @param element will be <code>null</code>, if a find method of <code>WebDriver</code> is called.120 * @param by locator being used121 * @param driver WebDriver122 */123 void afterFindBy(By by, WebElement element, WebDriver driver);124 /**125 * Called before {@link WebElement#click WebElement.click()}.126 *127 * @param driver WebDriver128 * @param element the WebElement being used for the action129 */130 void beforeClickOn(WebElement element, WebDriver driver);131 /**...
Source:CommonPage.java
...17 public CommonPage(WebDriver webDriver) {18 this.webDriver = webDriver;19 }20 public void openSideBar() {21 webDriver.findElement(By.id("react-burger-menu-btn")).click();22 }23 public boolean sidebarLinksValid(){24 WebElement inventoryLink = webDriver.findElement(By.id("inventory_sidebar_link"));25 WebElement aboutLink = webDriver.findElement(By.id("about_sidebar_link"));26 WebElement logoutLink = webDriver.findElement(By.id("logout_sidebar_link"));27 WebElement resetLink = webDriver.findElement(By.id("reset_sidebar_link"));28 return inventoryLink.getText().contains("ALL ITEMS")29 && aboutLink.getText().contains("ABOUT")30 && logoutLink.getText().contains("LOGOUT")31 && resetLink.getText().contains("RESET APP STATE");32 }33 public void goToCompanyFacebookPage() {34 String originalTab = webDriver.getWindowHandle();35 WebDriverWait wait = new WebDriverWait(webDriver, 10);36 wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("social_facebook")));37 webDriver.findElement(By.linkText("Facebook")).click();38 //a set of every tab created39 Set<String> allWindows = webDriver.getWindowHandles();40 Iterator<String> I1 = allWindows.iterator();41 while (I1.hasNext())42 {43 String child_window=I1.next();44 if(!originalTab.equals(child_window)){45 webDriver.switchTo().window(child_window);46 System.out.println(webDriver.switchTo().window(child_window).getTitle());47 break;48 }49 }50 }51 public void goToCompanyTwitterPage() {52 String originalTab = webDriver.getWindowHandle();53 WebDriverWait wait = new WebDriverWait(webDriver, 10);54 wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("social_twitter")));55 webDriver.findElement(By.linkText("Twitter")).click();56 //a set of every tab created57 Set<String> allWindows = webDriver.getWindowHandles();58 Iterator<String> I1 = allWindows.iterator();59 while (I1.hasNext())60 {61 String child_window=I1.next();62 if(!originalTab.equals(child_window)){63 webDriver.switchTo().window(child_window);64 System.out.println(webDriver.switchTo().window(child_window).getTitle());65 break;66 }67 }68 }69 public void goToCompanyLinkedInPage() {70 String originalTab = webDriver.getWindowHandle();71 WebDriverWait wait = new WebDriverWait(webDriver, 10);72 wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("social_linkedin")));73 webDriver.findElement(By.linkText("LinkedIn")).click();74 Set<String> allWindows = webDriver.getWindowHandles();75 Iterator<String> I1 = allWindows.iterator();76 while (I1.hasNext())77 {78 String child_window=I1.next();79 if(!originalTab.equals(child_window)){80 webDriver.switchTo().window(child_window);81 System.out.println(webDriver.switchTo().window(child_window).getTitle());82 break;83 }84 }85 }86 public Integer getCartBadgeNumber() {87 return null;88 }89 public Inventory clickAllItem() {90 return null;91 };92 public Login clickLogout() {93 webDriver.findElement(By.linkText("Logout")).click();94 return new LoginPage(webDriver);95 };96 public void clickResetAppState() {97 webDriver.findElement(By.id("reset_sidebar_link")).click();98 }99 public void goToCompanyAboutPage() {100 WebDriverWait wait = new WebDriverWait(webDriver, 10);101 wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("about_sidebar_link")));102 webDriver.findElement(By.id("about_sidebar_link")).click();103 }104 public Cart goToCartPage() {105 webDriver.findElement(By.className("shopping_cart_link")).click();106 return new CartPage(webDriver);107 }108 public String getUrl(){109 return webDriver.getCurrentUrl();110 }111}...
Source:ExplicitFluentWait.java
...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:GoogleExampleIT.java
...34 // not the implementation.35 WebDriver driver = getDriver();36driver.get("http://www.google.com");37driver.manage().window().maximize();38WebElement element = driver.findElement(By.name("q"));39element.sendKeys("Rent apartments near me ");40Thread.sleep(1000);41WebElement matchingResult= driver.findElement(By.xpath(".//div[@class='aajZCb']/ul"));42List<WebElement> listResult= matchingResult.findElements(By.xpath("//li/div/div[@class='sbtc']"));43System.out.println(listResult.size());44//if you want to print matching results45 for(WebElement results: listResult)46 {47 String value= results.getText();48 System.out.println(value);49 } 50 }51 @Test52 public void googleMilkExample() throws Exception {53 54 WebDriver driver = getDriver(); 55 driver.manage().window().maximize();56 57 driver.get("http://35.221.29.8:4200/");58 driver.findElement(By.linkText("List Users")).click();59 driver.findElement(By.linkText("Add User")).click();60 driver.findElement(By.id("name")).click();61 driver.findElement(By.id("name")).sendKeys("automationtest");62 driver.findElement(By.id("email")).click();63 driver.findElement(By.id("email")).sendKeys("automationtest@automationtest.com");64 driver.findElement(By.cssSelector(".btn:nth-child(4)")).click();65 66}}...
Source:SearchingEventListener.java
...19import org.openqa.selenium.WebDriver;20import org.openqa.selenium.WebElement;21public interface SearchingEventListener extends Listener {22 /**23 * Called before {@link org.openqa.selenium.WebDriver#findElement WebDriver.findElement(...)},24 * or25 * {@link org.openqa.selenium.WebDriver#findElements WebDriver.findElements(...)}, or26 * {@link org.openqa.selenium.WebElement#findElement WebElement.findElement(...)}, or27 * {@link org.openqa.selenium.WebElement#findElement WebElement.findElements(...)}.28 *29 * @param element will be <code>null</code>, if a find method of <code>WebDriver</code>30 * is called.31 * @param by locator being used32 * @param driver WebDriver33 */34 void beforeFindBy(By by, WebElement element, WebDriver driver);35 /**36 * Called after {@link org.openqa.selenium.WebDriver#findElement WebDriver.findElement(...)},37 * or38 * {@link org.openqa.selenium.WebDriver#findElements WebDriver.findElements(...)}, or39 * {@link org.openqa.selenium.WebElement#findElement WebElement.findElement(...)}, or40 * {@link org.openqa.selenium.WebElement#findElement WebElement.findElements(...)}.41 *42 * @param element will be <code>null</code>, if a find method of <code>WebDriver</code>43 * is called.44 * @param by locator being used45 * @param driver WebDriver46 */47 void afterFindBy(By by, WebElement element, WebDriver driver);48}
Source:Demo4.java
...27 }28 public static void main(String[] args) throws IOException, InterruptedException {29 WebDriver driver=new ChromeDriver();30 driver.get("D:\\Day11_july31\\ActionDemo.html");31 driver.findElement(By.id("A2")).click();32 Thread.sleep(1000);33 String xp="//span[text()='right click me']";34 WebElement element = driver.findElement(By.xpath(xp));35 Actions actions=new Actions(driver);36 actions.contextClick(element).perform();37 Thread.sleep(1000);38 driver.findElement(By.xpath("//span[text()='Quit']")).click();39 }4041}
...
Source:OpenEMRLogin.java
...16 System.out.println(title);17 String url=driver.getCurrentUrl();18 System.out.println(url);19 20 //driver.findElement(By.id("authUser")).sendKeys("admin"); 21 driver.findElement(By.xpath("//input[@id='authUser']")).sendKeys("admin");22 driver.findElement(By.id("clearPass")).sendKeys("pass");23 Select selectlanguage=new Select(driver.findElement(By.name("languageChoice")));24 selectlanguage.selectByValue("18"); //selectlanguage.selectByVisibleText("English (Indian)");25 driver.findElement(By.xpath("//button[@class='btn btn-login btn-lg']")).click();26 27 }28}...
Source:MyFirstScripts.java
...14 WebDriver driver=null; //It is an interface in java 15 System.setProperty("webdriver.chrome.driver", "C:\\Users\\Ganesh\\workspace\\WebDriverTraining\\Test\\Resources\\chromedriver-93.exe");16 driver = new ChromeDriver();17 driver.get("http://nichethyself.com/tourism/home.html");18 WebElement user = driver.findElement(By.name("username"));19 user.sendKeys("stc123");20 driver.findElement(By.name("password")).sendKeys("12345");//Method chaining in Java 21 driver.findElement(By.name("username")).submit();//submitting the form. 22 23 driver.quit();24 //WebDriver driver = new WebDriver();25 }26 2728}
...
findElement
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 java.util.concurrent.TimeUnit;6import org.openqa.selenium.By;7import org.openqa.selenium.WebDriver;8import org.openqa.selenium.WebElement;9import org.openqa.selenium.chrome.ChromeDriver;10import java.util.concurrent.TimeUnit;11import org.openqa.selenium.By;12import org.openqa.selenium.WebDriver;13import org.openqa.selenium.WebElement;14import org.openqa.selenium.chrome.ChromeDriver;15import java.util.concurrent.TimeUnit;16import org.openqa.selenium.By;17import org.openqa.selenium.WebDriver;18import org.openqa.selenium.WebElement;19import org.openqa.selenium.chrome.ChromeDriver;20import java.util.concurrent.TimeUnit;21import org.openqa.selenium.By;22import org.openqa.selenium.WebDriver;23import org.openqa.selenium.WebElement;24import org.openqa.selenium.chrome.ChromeDriver;25import java.util.concurrent.TimeUnit;26import org.openqa.selenium.By;27import org.openqa.selenium.WebDriver;28import org.openqa.selenium.WebElement;29import org.openqa.selenium.chrome.ChromeDriver;30import java.util.concurrent.TimeUnit;31import org.openqa.selenium.By;32import org.openqa.selenium.WebDriver;33import org.openqa.selenium.WebElement;34import org.openqa.selenium.chrome.ChromeDriver;35import java.util.concurrent.TimeUnit;36import org.openqa.selenium.By;37import org.openqa.selenium.WebDriver;38import org.openqa.selenium.WebElement;39import org.openqa.selenium.chrome.ChromeDriver;40import java.util.concurrent.TimeUnit;41import org.openqa.selenium.By;42import org.openqa.selenium.WebDriver;43import org.openqa.selenium.WebElement;44import org.openqa.selenium.chrome.ChromeDriver;45import java.util.concurrent.TimeUnit;46import org.openqa.selenium.By;47import org.openqa.selenium.WebDriver;48import org.openqa.selenium.WebElement;49import org.openqa.selenium.chrome.ChromeDriver;50import java.util.concurrent.TimeUnit;51import org.openqa.selenium.By;52import org.openqa.selenium.WebDriver;53import org.openqa.selenium.WebElement;54import org.openqa.selenium
findElement
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;5public class FindElementAndSendKeysAndClick {6 public static void main(String[] args) {7 System.setProperty("webdriver.chrome.driver", "C:\\Program Files\\Java\\chromedriver.exe");8 WebDriver driver = new ChromeDriver();9 WebElement searchBox = driver.findElement(By.name("q"));10 searchBox.sendKeys("Selenium");11 searchBox.submit();12 driver.quit();13 }14}
findElement
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;5public class ClickElement {6public static void main(String[] args) {7System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");8WebDriver driver = new ChromeDriver();9WebElement element = driver.findElement(By.id("gb_70"));10element.click();11driver.close();12}13}14List<WebElement> findElements(By by)15import org.openqa.selenium.By;16import org.openqa.selenium.WebDriver;17import org.openqa.selenium.WebElement;18import org.openqa.selenium.chrome.ChromeDriver;19public class FindElements {20public static void main(String[] args) {21System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");22WebDriver driver = new ChromeDriver();23List<WebElement> elementList = driver.findElements(By.tagName("a"));24System.out.println(elementList.size());25driver.close();26}27}
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!!