Selenium Webdriver – 10 Coding Tips To Improve
Quality
Tip-1: Best Method To Create Webdriver Instance.
public class DriverFactory {
private WebDriver driver = null;
public static WebDriver getBrowser(String browserType) {
if (driver == null) {
if (browserType.equals("Firefox"))
{
driver = new FirefoxDriver();
} else if (browserType.equals("Chrome"))
{
driver = new ChromeDriver();
} else if (browserType.equals("IE"))
{
driver = new InternetExplorerDriver();
}
}
return driver;
}
}
Tip-2: Simple Method To Check If An Element Exists.
Boolean isItemPresent = driver.findElements(By.testLocator).size() > 0
Tip-3: Avoid Exception While Checking An Element Exists.
/* 1- Test if an element exists on the page.
2- Ignore the no element found exception.
*/
By element = By.xpath(".//*[@id='demo']/p");
Wait < WebDriver > wait = new FluentWait < > (driver)
.withTimeout(60, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
wait.until(ExpectedConditions
.presenceOfElementLocated(element));
Tip-4: Wait For A Page With JavaScript(JS) To Load.
wait.until(new Predicate < WebDriver > () {
@Override
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor) driver).executeScript("return
document.readyState").equals("complete");
}
});
Tip-5: Take A Screenshot Using Webdriver.
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
// Store the screenshot in current project dir.
String screenShot = System.getProperty("user.dir") + "\\screenShot.png";
// Call Webdriver to click the screenshot.
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
// Save the screenshot.
FileUtils.copyFile(scrFile, new File(screenShot));
Tip-6: How To Select/Get Drop Down Option In Selenium
Webdriver.
Select dropdown = new Select(driver.findElement(By.xpath("//drop_down_x_path")));
dropdown.deselectAll();
dropdown.selectByVisibleText("selectLabel");
Tip-7: Refreshing Web Page By WebDriver During Tests.
driver.navigate().refresh();
Tip-8: Run A JavaScript Code Using Selenium Webdriver.
JavascriptExecutor JS = (JavascriptExecutor) driver;
JS.executeScript("alert('hello world')");
Tip-9: Open A New Tab Using Selenium WebDriver In Java.
- driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
- ArrayList<String> tablist = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tablist.get(0));
Tip-10: Switch To A New Browser Window In Webdriver.
// Get the current window handle.
String hBefore = driver.getWindowHandle();
// Click to open new windows.
// Switch to new windows.
for(String hNew: driver.getWindowHandles()){
driver.switchTo().window(hNew);
}
// Close all new windows.
driver.close();
// Switch back to first window.
driver.switchTo().window(hBefore);
// Resume your work.