Efficient Selenium Scripting and Troubleshoot Scenarios – Selenium Tutorial #27

By Vijay

By Vijay

I'm Vijay, and I've been working on this blog for the past 20+ years! I’ve been in the IT industry for more than 20 years now. I completed my graduation in B.E. Computer Science from a reputed Pune university and then started my career in…

Learn about our editorial policies.
Updated December 2, 2024

In the previous tutorial, we discussed the technical implications of implementing logging in a framework. We discussed log4j utility at length.

We discussed the basic components that constitute log4j from a usability perspective. With the Appenders and layouts, a user is leveraged to choose the desired logging format/pattern and the data source/location.

In the current 27th tutorial in this comprehensive free selenium online training series, we would shift our focus towards a few trivial yet important topics that would guide us in troubleshooting some recurrent problems. We may or may not use them in daily scripting, but they would be helpful in the long run.

Selenium Scripting and Troubleshooting

Selenium Scripting And Troubleshoot Scenarios

We would discuss some advanced concepts wherein we would deal with mouse and keyboard events, and accessing multiple links by implementing lists. So let’s just dive in and talk about these topics using examples and code snippets.

JavaScript Executors

While automating a test scenario, certain actions become an inherent part of test scripts.

These actions may be:

  • Clicking a button, hyperlink, etc.
  • Typing in a text box
  • Scrolling Vertically or Horizontally until the desired object is brought into view
  • And much more

Now, it is clear from the earlier tutorials that the best way to automate such actions is by using Selenium commands.

But what if the selenium commands don’t work?

Yes, it is possible that the elementary Selenium Commands don’t work in certain situations. So, to troubleshoot this, we bring in JavaScript executors.

What are JavaScript Executors?

JavaScript Executors

JavascriptExecutor interface is a part of org.openqa.selenium and implements java.lang.Object class. JavascriptExecutor presents the capabilities to execute JavaScript directly within the web browser. To execute the JavaScript, certain mechanisms, as methods along with a specific set of parameters, are provided in its implementation.

Methods

executeScript (String script, args)

As the method name suggests, it executes the JavaScript within the current window, alert, frame, etc (the window that the WebDriver instance is currently focusing on)

executeAsyncScript (String script, args)

As the method name suggests, it executes the JavaScript within the current window, alert, frame etc (the window that the WebDriver instance is currently focusing on)

The parameters and import statement are common to both the executor methods.

Parameters
Script – the script to be executed
Argument – the parameters that the script requires for its execution (if any)

Import statement
To use JavascriptExecutors in our test scripts, we need to import the package using the following syntax:

import org.openqa.selenium.JavascriptExecutor;

Sample Code

#1) Clicking a web element

// Locating the web element using id
WebElement element = driver.findElement(By.id("id of the webelement"));
 
// Instantiating JavascriptExecutor
JavascriptExecutor js = (JavascriptExecutor)driver;
 
// Clicking the web element
js.executeScript("arguments[0].click();", element);

#2) Typing in a Text Box

// Instantiating JavascriptExecutor
JavascriptExecutor js = (JavascriptExecutor)driver;
 
// Typing the test data into Textbox
js.executeScript("document.getElementById(‘id of the element’).value=’test data’;”);

#3) Scrolling down until the web element is in the view

WebElement element=driver.findElement(By.xpath("//input[contains(@value,'Save')]"));
 
// Instantiating the javascriptExecutor and scrolling into the view in the single test step
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView(true);",element);

You may find various other ways of writing the code for accessing JavascriptExecutors.

Accessing Multiple Elements in a List

We may come across elements of the same type, like multiple hyperlinks, images, etc arranged in an ordered or unordered list. So, it makes sense to handle all those elements with just one code, using WebElement List.

Refer to the screenshot below to understand the elements I am talking about.

Selenium scripting tips 1

In the above image, we see that the various service providers belong to an unordered list. Thus, verification of clickability and visibility of these elements can be done by a single piece of code by using a list of elements.

Import statement
To be able to use a WebElement list in our test scripts, we need to import the package using the following syntax:

import java.util.List;

Sample Code

// Storing the list
List <WebElement> serviceProviderLinks = driver.findElements(By.xpath("//div[@id='ServiceProvider']//ul//li"));
 
// Fetching the size of the list
int listSize = serviceProviderLinks.size();
for (int i=0; i<listSize; i++)
{
 
// Clicking on each service provider link
serviceProviderLinks.get(i).click();
 
// Navigating back to the previous page that stores link to service providers
driver.navigate().back();
}

There are various requirements under which the lists can verify the elements with suitable implementation changes.

Handling Keyboard and Mouse Events

Handling Keyboard Events

As also said earlier, there are n number of ways to deal with the same problem statement in different contexts.

Thus, a necessity arises to deal with a problem by changing the conventional dealing strategy with a more advanced strategy. I have witnessed cases where I could not deal with alerts and pop up etc. by selenium commands thus I had to opt for different Java utilities to deal with it using keyboard strokes and mouse events.

Robot class is one such option to perform keyboard events and mouse events. Let us understand the concept with the help of a scenario and its implementation.

Scenario:

Imagine a situation where a stupid pop up shows up on the screen and we can’t get rid of it using the Alert Interface. So, the only option left is to close the window with the shortcut keys “Alt + spacebar + C”. Let us see how we close the popup using Robot Class.

Before, initiating the implementation, we should import the necessary package to be able to use the Robot class within our test script.

Import Statement

import java.awt.Robot;

Sample Code

// Instantiating Robot class
Robot rb =new Robot();
 
// Calling KeyPress event
rb.keyPress(KeyEvent.VK_ALT);
rb.keyPress(KeyEvent.VK_SPACE);
rb.keyPress(KeyEvent.VK_C);
 
// Calling KeyRelease event
rb.keyRelease(KeyEvent.VK_C);
rb.keyRelease(KeyEvent.VK_SPACE);
rb.keyRelease(KeyEvent.VK_ALT);

Robot class can also be used to handle mouse events but let us here look at the selenium’s capabilities to handle mouse events.

Handling Mouse Events

WebDriver offers a wide range of interaction utilities that the user can exploit to automate mouse and keyboard events. Action Interface is one such utility that simulates single-user interactions.

Thus, we would witness Action Interface to mouse hover on a drop down, which then opens a list of options in the next scenario.

Scenario:

  1. Mouse Hover on the dropdown
  2. Click on one item in the list options

Import Statement

import org.openqa.selenium.interactions.Actions;

Sample Code

// Instantiating Action Interface
Actions actions=<strong>new</strong> Actions(driver);
 
// howering on the dropdown
actions.moveToElement(driver.findElement(By.<em>id</em>("id of the dropdown"))).perform();
 
// Clicking on one of the items in the list options
WebElement subLinkOption=driver.findElement(By.id("id of the sub link"));
subLinkOption.click();

Conclusion

In this tutorial, we discussed some advanced topics related to efficient scripting and troubleshooting scenarios where the user is required to handle mouse and keyboard events. We also discussed how to store more than one web element in a list. I hope you can handle these issues if they come up.

Next Tutorial #28: For the upcoming tutorial in the series, we will discuss the concept of Database testing using Selenium WebDriver. We would witness the mechanism of database connection, hitting selenium queries and fetching the results through Selenium WebDriver Code.

Was this helpful?

Thanks for your feedback!

Recommended Reading

  • Cucumber Java Selenium WebDriver Integration

    Cucumber Selenium WebDriver Java Integration with Example: In the last tutorial, we discussed the Cucumber tool, its usage, and different features. Moving ahead in our free Selenium online training series, we will discuss how to set up a cucumber project and will discuss the integration of Selenium WebDriver with Cucumber.…

  • Introduction To Selenium WebDriver

    Introduction to Selenium WebDriver: Earlier in this series, we published tutorials that focused more on Selenium IDE and its various aspects. We introduced the tool and discussed its features. We also constructed a few scripts using Selenium IDE and Firebug. From there, we moved on to different types of web…

  • Selenium on Chrome

    In-Depth Tutorial On ChromeDriver for Running Selenium Webdriver Tests on Chrome Browser: Handling browser alerts while automating through Selenium will be discussed in this article. Moreover, we will elaborate on the set up of the Selenium script for the Google Chrome browser along with appropriate examples and pseudo-codes. Upon going…

  • Selenium Tutorials

    A Complete List of the Best Selenium Tutorials to Learn and Master Selenium From Scratch:  After several frequent requests from STH readers, today we are finally launching our FREE Selenium Tutorial series. In this Selenium training series, we will cover all Selenium testing concepts and its packages with easy-to-understand practical…

  • selenium automation with phantomjs

    In This Article, Selenium Automation With PhantomJS is Explained With Code Examples: PhantomJS is a headless browser that is primarily used for GUI less automation. The performance and execution happening on this browser is faster and is generally used in the scenarios where manual monitoring is not required and on…

  • FIND ELEMENT BY TEXT

    An In-Depth Look at Selenium Find Element by Text with Example: Selenium Find Element That Contains Specific Text Selenium Find element by text is used to locate a web element using its text value. The text value is generally used when the basic element identification properties such as ID or…

  • Locate Elements in Chrome and IE Browsers

    This is tutorial #7 in our Selenium Online Training Series. If you want to check all Selenium tutorials in this series, please check this page. In the previous tutorial, we tried to shed light on various types of locators in Selenium and their locating mechanisms to build test scripts. The…

  • Introduction to JUnit Framework

    This tutorial will give an insight into JUnit and its usage in selenium script. This is tutorial #11 in our comprehensive Selenium tutorials series. JUnit is an open-source unit testing tool used to test small/large units of code. To run the JUnit test, you don’t have to create a class…


3 thoughts on “Efficient Selenium Scripting and Troubleshoot Scenarios – Selenium Tutorial #27”

  1. What is the difference between executeScript (String script, args) and executeAsyncScript (String script, args), both seems to me same as per description provided.

    Reply
  2. The explanations of the methods executeScript and executeAsynScript are exactly the same.

    The Selenium documentation states this is the difference:
    Execute an asynchronous piece of JavaScript in the context of the currently selected frame or window. Unlike executing synchronous JavaScript, scripts executed with this method must explicitly signal they are finished by invoking the provided callback. This callback is always injected into the executed function as the last argument.

    Reply

Leave a Comment