Return to site

Selenium Scripting Tips and Tricks

Tutorial on Selenium Scripting Tips and Tricks with Code Snippets and ScreenShots

· testing service
broken image

If you have just started learning selenium then the below tricks and tips will act as a saviour. These tips and tricks have all the basic things which you might forget and it will help you in remembering all those. You can just go through them once and you will get to know everything in few seconds. Let’s have a look at all the tricks and tips one by one.

  • Best Way to Create Webdriver Instance

You can make your tests generic. First step would be initializing the browser by passing the value from the configuration file. You can have one key as browser and value as Chrome, Firefox or IE. You can then initialize the browser according to the value passed there. Let’s look at the code which will be involved.Add paragraph text here.

public static WebDriver getBrowser(String browserName)

{

If(driver == null)

if(browserName.equals(“firefox”))

{

driver = new FirefoxDriver();

}

else if(browserName.equals(“Chrome”))

{

driver=new ChromeDriver();

}

else if(browserName.contains(“IE”))

{

driver=new InternetExplorerDriver();

}

}

return driver;

}

  • Best Way To Check If An Element Exists Or Not

If you have to check whether an element exist in the web application or not, you can easily do it by getting the size of the web element and then check if it is greater than zero or not.

Boolean isElementExists = driver.findElements(By.xpath(“”)).size()>0

  • How To Wait For Page To Load Completely?

Sometimes, a page takes some time to load and you have to then wait for the time till the page is loaded completely. For this, you have to first check if it is loaded properly and then you can do any other operation on it. You can use Javascriptexecutor to check if the page is loaded completely or not.

wait.until(new Predicate < WebDriver > () {

@Override

public Boolean waitPageLoaded(WebDriver driver) {

return ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete");

}

});

  • How To Take A Screenshot Using Selenium 

Webdriver?

Sometimes, it is very important to take screenshots while execution to know what went wrong. It is damn say to do it with selenium. You can have selenium driver and then you can cast it to takes Screenshot interface. Make an instance of it and then use it to get the screenshot. You can use kits method .getScreenshotAs and then you can specify in which format you are expecting your screenshots to be.

// Storing the screenshot in current project directory

String screenShot = System.getProperty("user.dir") + "\\screenshottest.png";

//casting Webdriver to take the screenshot

File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

// Saving the screenshot

FileUtils.copyFile(srcFile, new File(screenShot));

  • How To Get HTML Source Of Web Element In Selenium 

Webdriver?

Selenium WebDriver provides you one method named getAttribute which will allow you to get inner HTML of a web element. You can do it by getting the element first. Afterwards, you can use getAttribute to get the innerHTML of a web element.

String html = element.getAttribute("innerHTML");

  • How To Select Dropdown Options Using Select Class?

In selenium, if you encounter any dropdown then you can select any option in it using select class. There are many ways by which you can select an option. Some of the ways include selecting by text, index and values. 

Select drp= new Select(Driver.findElement(By.xpath(“”));

drp.deselectAll();

drp.selectByVisibleText("selectLabel");

  • How To Refresh Web Page In 

Webdriver?

If you want to refresh the page then you can use navigate () method of selenium web driver. You can then refresh() method to actually refresh the page so that all elements will be initlitzed from the starting.

driver.navigate().refresh();

  • How To Switch To New Tab Using Selenium 

Webdriver?

You can easily switch to new tab using selenium webdriver. First thing to keep in mind is to use .getWindowHandles() and then you can switch to the first index of the array list having all the window handles.

ArrayList tabs = new ArrayList (driver.getWindowHandles());

driver.switchTo().window(tabs.get(0));

  • How to Set Driver Executable Path in 

Webdriver?

For browsers, chrome and i.e., you have to see path for the driver executables. For setting the path you have to use System.setProperty method in selenium. Let’s see how it looks.

File ieDriverPath = new File("path//iexploredriver.exe");

System.setProperty("webdriver.ie.driver", ieDriverPath.getAbsolutePath());

WebDriver driver = new InternetExplorerDriver(); 

  • How to Switch To New Popup Window? 

If you want to switch to a specific window which is opened then you can first getAllWindowHandles() and then switch using method driver.switchTo().

// Get the current window handle.

String hBefore = driver.getWindowHandle();

// action which opens lot of 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);

But if in case, you want to specifically switch to a particular window. You can get a web element and see the visibility of it in a particular window. If it is present, then you can switch to it.

// Get the current window handle.

String hBefore = driver.getWindowHandle();

// Click to open new windows.

// Switch to window which has a webelement attached to it

for(String hNew: driver.getWindowHandles()){

If(driver.findElements(By.xpath(“”)).size()>0)

{

driver.switchTo().window(hNew);

}

}

// Close all new windows.

driver.close();

// Switch back to first window.

driver.switchTo().window(hBefore);

  • How to Click On a Checkbox Which Isn’t Visible?

There are many instances when the checkbox you want to click isn’t visible and unfortunately you won’t be able to click on it. You have to first enable it so that you can actually click on it. If you won’t enable it then you would get exception like “Element is not currently visible and so may not be interacted with."

Java script executor can be used to enable it so that selenium can click on it. Code snippet is below:

((JavascriptExecutor)driver).executeScript("arguments[0].checked = true;", checkbox);

  • How to Do Mouseover Action in Selenium Webdriver?  

If you want to mouse over a web element, you can use Actions() class to handle it. You can use function moveToElemenet() and then build() and perform() in a sequence to perform mouse hovering action on a web element.

Actions action = new Actions(driver);

WebElement item = driver.findElement(By.xpath(""));

action.moveToElement(item).moveToElement(driver.findElement(By.xpath("")) ).click().build().perform();

  • How to Delete Cookies before Running a Test Script? 

Sometimes it is very important to clear all the cookies before running your test scripts. You can use method DeleteAllCookies function of driver.manage().

The code snippet is as below:

this.driver.Manage().Cookies.DeleteAllCookies();

Also, if you have a cookie which is having a particular name then you can delete it using method: DeleteCookiesNames of manage() class.

this.driver.Manage().Cookies.DeleteCookieNamed("CookieName");

  • How to Maximize the Window in the Test Script?

Sometimes, you need to test the scripts in full window size and resolution. You can easily do it by using manage () method of driver instance. You can then use method window() and then maximize() to take the window to the maximum size.

Code snippet is as below:

public void MaximizeWindow()

{

this.driver.get(“");

this.driver.Manage().Window().Maximize();

}

Conclusion

Selenium is the best tools for automation testing and it is used by most of the QA Automation Testing Services provider. So, there are some important tricks and tips which you can follow to run your selenium tests. If you will keep these in mind, you will solve majority of your problems while scripting in Automation Testing. So, use them and save your time. All the best!!