Selenium WebDriver Event Listener
Last Updated :
05 Aug, 2024
Testing Websites often includes testing multiple pages in the website. "Selenium" is one of the most popular test automated frameworks used to test multiple web pages provides numerous functionalities and enables the interaction between web pages. The name "Listeners" suggests that they can listen to any particular event and they are often used for customizing the reports and logs.
There are mainly two types of Listeners in the selenium used by Java they are:
- WebDriver Listeners
- Testing Listeners
Generally, the WebDriverEventListener is an interface that is used to implement the classes like:
- WebDriverEventListener (deprecated)
- EventFiringDecorator
- EventFiringWebDriver ( deprecated )
It is used to implement methods like beforeClick, afterClick, beforeFindElement, afterFindElement, beforeNavigateTo, afterNavigateTo, onError, and many more methods. We can also define the eventListener as an interface that is used as an observer to monitor specific actions in the WebDriver.By implementing an event listener we can do the below-mentioned actions.
- Navigation of URLs
- Find Elements
- Click Elements
- Error Handling and many more actions
Let's more understand this clearly. Now we will implement a code to extract all the href attributes from the anchor tag and know the action of the event Listener class in the web driver event Listener interface in the selenium web driver.
Step-by-step guide:
- Install JDK and JRE on your desktop or pc.
- Install an IDE let it be Visual Studio code.
- Install the selenium on your computer and chromeDriver.exe in your system to automate the websites using the web driver.
- press CTRL+SHIFT+P and select the option Java project
- Select the build tool MAVEN or GRADLE.
- Select the Maven with the simple arch type.
- In the pom.xml add the dependency tag of selenium.
The Directory structure of the project looks like this. <dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>${selenium.version}</version>
</dependency>
This will include the dependency of the selenium in your laptop.
Adding dependency of selenium Program to implement the eventlistener in the Selenium:
- The above steps will create a java project for us and let the package name be given as " com.example" and the classes be the Main.java where the program is implemented
- Import the necessary packages from the selenium to implement the code in the selenium.
Main.java
Java
// Define the package name
package com.example;
// Import the Selenium package as declared in the pom.xml with the dependency tag
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.events.EventFiringDecorator;
import java.util.*;
public class Main {
public static void main(String[] args) {
// Set up the Chrome WebDriver
System.setProperty("webdriver.chrome.driver", "C:\\Program Files\\chromedriver-win64\\chromedriver.exe");
// Create an instance of WebDriver
WebDriver driver = new ChromeDriver();
// Create an instance of the event listener
MywebDriver eventListener = new MywebDriver();
// Wrap the WebDriver instance with the EventFiringDecorator to listen to events
WebDriver decoratedDriver = new EventFiringDecorator<>(eventListener).decorate(driver);
// Open the URL
try {
decoratedDriver.navigate().to("https://www.geeksforgeeks.org/");
// Wait for the page to load and find all elements with the tag name "a"
List<WebElement> array = decoratedDriver.findElements(By.tagName("a"));
// Extract and print the href attributes of the first 10 anchor tags
System.out.println("Extracting the href attributes from the first 10 anchor tags:");
for (int i = 0; i < 10; i++) {
System.out.println(array.get(i).getAttribute("href"));
}
} catch (Exception e) {
// Close the driver in case of an exception
decoratedDriver.quit();
}
}
}
Output:
Extracting all the anchor tags nd from the elements from the WebElement
https://www.geeksforgeeks.org/
https://practice.geeksforgeeks.org/courses/
https://www.geeksforgeeks.org/courses/dsa-to-development-coding-guide?itm_source=geeksforgeeks&itm_medium=main_header&itm_campaign=courses
https://www.geeksforgeeks.org/courses?itm_source=geeksforgeeks&itm_medium=main_header&itm_campaign=courses
https://www.geeksforgeeks.org/videos/
https://www.geeksforgeeks.org/jobs
https://www.geeksforgeeks.org/gfg-hiring-solutions-for-recruiters/
https://www.geeksforgeeks.org/videos/
https://www.geeksforgeeks.org/jobs
https://www.geeksforgeeks.org/gfg-hiring-solutions-for-recruiters/
Output:
Extracted all the href attributes from the Geeks For Geeks Website
Step-by-step explanation:
- In the above code we are importing the selenium package from the java.
- We are setting up the property as chrome.driver and path of the chrome driver .exe we have installed in our computer .
- We have to instantiate the object for the ChromeDriver().
- Then we have to instantiate the object for the MywebDriver which implements the WebDriverListener().
- Now we have to wrap the event driver with the firing decorator.
- We will open the url.
- Now we will find the elements with the help of the tag name using By class.
- we will extract the href attribute using the anchor tags.
- we will extract the 10 hrefs .
- We will quit the driver .
MyWebDriver.java
Java
package com.example;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.events.WebDriverListener;
public class MywebDriver implements WebDriverListener {
@Override
public void beforeClick(WebElement element){
System.out.println("Before Clicking on the element :"+element.toString());
}
@Override
public void afterClick(WebElement element){
System.out.println("After clicking on the element the element is "+element.toString());
}
@Override
public void beforeFindElement(WebDriver driver , By locator){
System.out.println("Before finding the element "+locator.toString());
}
@Override
public void afterFindElement(WebDriver driver , By locator,WebElement result){
System.out.println("After finding the element "+locator.toString());
}
public void beforeNavigateTo(String url,WebDriver driver){
System.out.println("Before Clicking on the url"+url);
}
public void afterNavigateTo(String url,WebDriver driver ){
System.out.println("After Clicking on the url"+url);
}
public void onError(WebDriver driver,Throwable throwable){
System.out.println("Exception occured"+throwable);
}
}
Output:
Before navigating to: https://www.geeksforgeeks.org/
After navigating to: https://www.geeksforgeeks.org/
Before finding element: By.tagName: a
After finding element: By.tagName: a
Conclusion:
The selenium is very best tool for automation testing and enhance the reading the scripts from the web site . So the usage of the event listener helps us to maintain the logs and it can be utilised to handle the errors. It helps us to enhance the test scripts without the disturbance of code.
Similar Reads
Selenium WebDriver-Handling Alerts Selenium is one of the most popular and powerful tools for automated web applications. Selenium is widely used for automating user interactions like filling out forms, navigating to a website clicking on a button, etc. While we are dealing with automating user interactions one of the most common sce
5 min read
Selenium WebDriver Commands Selenium WebDriver is a powerful tool for automating the web browser to perform certain tasks. Selenium supports multiple browsers (such as Chrome, Firefox, Edge, Safari, etc.) and multiple programming languages (such as Java, Python, C#, etc.) so, it is very easy to use and automate tasks on a brow
7 min read
Architecture of Selenium WebDriver Selenium WebDriver is a powerful tool for automating web browsers. Its architecture comprises various key components, including the Selenium Client Library, WebDriver API, Browser Drivers, and the Browser itself. The Selenium Client Library provides language-specific bindings for interacting with We
7 min read
Find Web Elements using Selenium WebDriver We can identify web elements in the web page using the following two tools: Developer Tools FireBug and FirePath Developer Tools - Right-click on the web page. Navigate to inspect element to find the developer's tool. Note: There are some websites where the right-click is disabled. eg. IRCTC, bankin
4 min read
How to click on hidden element in Selenium WebDriver? In Selenium WebDriver, interacting with web elements is key to automating web applications. However, certain elements on a webpage might be hidden or obscured, making it challenging to interact with them directly. In such cases, developers and testers often need to use alternative methods, such as J
3 min read
Selenium Webdriver submit() vs click() When working with Selenium WebDriver for web automation, you often need to interact with web elements like forms and buttons. Two commonly used methods for triggering actions in Selenium are submit() and click(). Understanding the differences between submit() and click() is crucial for effective tes
5 min read
Key press in (Ctrl+A) Selenium WebDriver using java Selenium WebDriver is a powerful tool for automating web applications, and it offers various ways to simulate user actions such as clicking, typing, and even pressing keyboard shortcuts. One of the common actions is selecting all text or elements on a page using the "Ctrl+A" key press. This is usefu
3 min read
Difference Between WebDriver and Web Element? Although WebDriver helps with browser control and navigation, WebElements are the building blocks of automated test scripts that help find and interact with specific elements within web pages. Table of Content What is WebDriver?What is WebElement?Methods of WebDriver and WebElementDifference between
5 min read
How to check if an element exists with Selenium WebDriver? Selenium is one of the most popular tools for automating web applications. Selenium is not a single tool but rather a set of tools that helps QA testers and developers to automate web applications. It is widely used to automate user interactions on a web page like filling out web forms, clicking on
7 min read