10 Selenium Webdriver Tips and Tricks

Ankit Agrawal
Javarevisited
Published in
3 min readApr 26, 2021

Many times we face some simple issues while working with Selenium Webdriver. Few simple steps can increase the stability and execution speed of the automated test. I have listed down various use cases faced in real time while working on Selenium with Java. Also listed down code snippets for these use cases which can be used directly.

1. Taking screenshot of Webpage(For Failures/Issues)

It is sometimes, required to take screenshot of webpage. It helps to identify problem and debug test case.

Screenshot is taken using following code snippet

File scrFile ;
String pathofscreenshot;
scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(pathofscreenshot + "\\screenshot.png"));

2. Take partial screenshot

Sometimes it is required to take screenshot of a part of screen. For example, we require to take screenshot of a popup or a frame in webpage.

To take partial screenshot use following code snippet

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

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

Point p = webelement.getLocation();

int width = webelement.getSize().getWidth();

int height = webelement.getSize().getHeight();

BufferedImage img = ImageIO.read(screen);

BufferedImage dest = img.getSubimage(p.getX(), p.getY(), width,height);

ImageIO.write(dest, "png", screen);

FileUtils.copyFile(screen, new File(pathofscreenshot + "\\screenshot.png"));

3. Execute javascript(.js)

We can execute javascript to do custom synchronizations, change some values, enable/disable element or hide/show elements.

Use following code to execute javascript using selenium webdriver

JavascriptExecutor js = ((JavascriptExecutor) driver);
js.executeScript("alert('hello world');");

4. select/get drop down option from list.

Use Select class to identify dropdown element

Select selectValue = new Select(webelement1);

To select option by index

selectValue.selectByIndex(<index in integer>);

To select option by value

selectValue.selectByValue(<string value of dropdown option>);

5. Using Drag and Drop Feature

Sometimes it is required to move element from one position to another. Dragging and dropping is not available in basic methods provided for webelement.

To do this use, Action class provided by selenium

Use following code snippet to drag from element webElementFrom to WebelementTo

Actions action = new Actions(driver);Action dragAndDrop = action.clickAndHold(webElementFrom)
.moveToElement(WebelementTo)
.release(WebelementTo)
.build();
dragAndDrop.perform();

6. Scrolling webpage(Vertical & Horizontal)

In selenium webdriver, scrolling can be done using javascriptexecutor. Call javascript function window.scrollBy in js executor.

((JavascriptExecutor)driver).executeScript("window.scrollBy(0,250);");

This will scroll webpage vertically by 250 pixels.

((JavascriptExecutor)driver).executeScript("window.scrollBy(250,0);");

This will scroll webpage horizontally by 250 pixels.

7. Open a new tab

Sometimes it is required to open a new tab in the same window of browser To open a new tab use following code snippet

driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");

After running test on new tab, use following code to switch to first tab again

ArrayList<String> tab_list=new ArrayList<String> (driver.getWindowHandles()); driver.switchTo().window(tab_list.get(0));

8. Set page Load TimeOut

Sometimes webpage takes some time to load completely. To set page loading timeout use following code snippet

driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);

This will timeout the page after 40 seconds.

9. Refreshing webpage

Sometimes it happens in webpage that elements are not loaded and page needs to be refreshed to load all elements. In most of the cases, it is seen that elements don’t load on first attempt but if we load page again, all components are loaded

There are many ways to refresh webpage using selenium. Some of the ways are as below:

driver.navigate().refresh();
driver.navigate().to(driver.getCurrentUrl());

Lets say current application url is google.co.in

driver.get("https://www.google.co.in");

We can send F5 key over any element

driver.findElement(By.id("id1")).sendKeys(Keys.F5);
driver.findElement(By.id("id1")).sendKeys("\uE035");

here, \uE035 is the ASCII code of id1

When we execute location.reload function using javascript executor, current webpage gets loaded

$ JavascriptExecutor js; $ js.executeScript("location.reload()");

10. Switch between browser windows

Sometimes on clicking on an element, webpage opens a new popup window and it is required to switch driver instance to the new window and perform some operation.

Use following code snippet.

//Get the current window handle

String currentwindowhandle = driver.getWindowHandle();



//Click to open new windows.
....
....
....


//Switch to new window

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

driver.switchTo().window(newwindowhandle);

}



//Close new window

driver.close();



//Switch back to first window

driver.switchTo().window(currentwindowhandle);

Originally published at https://www.linkedin.com.

--

--