Overview
In this tutorial, we will learn some of the useful Webdriver code snippets useful across test automation programs.
How to Accept Alert?
public void AcceptAlert() throws Throwable { boolean status = false; Alert alert = null; try { alert = driver.switchTo().alert(); alert.accept(); status = true; } catch (NoAlertPresentException ex) { ex.printStackTrace(); } finally { if (status) { System.out.println("Alert Success "); } else{ System.out.println("Alert Failure : no alert to handle"); } } }
How to wait for visibility of Element on a web page ?
public boolean waitForVisibilityOfElement(By by) throws Throwable { boolean status = false; wait = new WebDriverWait(driver, 45); try { wait.until(ExpectedConditions. visibilityOfElementLocated(by)); status = true; return status; } catch (Exception e) { return status; } finally { if (status ) { System.out.println("wait for visibility success "); } else { System.out.println("wait for visibility failed"); } } }
How to wait for invisibility of Element on a web page ?
The code snippet is almost same as above except for a small change.
public boolean waitForInVisibilityOfElement(By by) throws Throwable { boolean status = false; wait = new WebDriverWait(driver, 45); try { wait.until(ExpectedConditions. invisibilityOfElementLocated(by)); status = true; return status; } catch (Exception e) { return status; } finally { if (status) { System.out.println("wait for invisibility success... "); } else { System.out.println("wait for invisibility failure... "); } } }
How to get HTML table row count ?
public int getTableRowCount(By locator) throws Exception { WebElement table = driver.findElement(locator); List<WebElement> rows = table.findElements(By.tagName("tr")); int rowcount = rows.size() - 1; return rowcount ; }
How to get HTML table column count?
public int getTableColumncount(By locator) throws Exception { WebElement tr = driver.findElement(locator); List<WebElement> columns = tr. findElements(By.tagName("td")); int colcount = columns.size() ; return colcount; }
Selenium Tutorial on this website:
https://www.testingdocs.com/selenium-webdriver-tutorial/
More information on Selenium, visit official website: