Turn your manual testers into automation experts! Request a DemoStart testRigor Free

WebDriverException in Selenium: How to Resolve

In Selenium, we use the WebDriver library for automating web browser interactions. The exceptions in Selenium are errors that can occur during the automation of web applications with Selenium WebDriver. They interrupt the normal test execution flow. In this article, we are going in-depth about the WebDriverException, how it happens, and how to avoid it.

Let’s go through the common causes for WebDriverException.

Reasons for WebDriverException

WebDriverException typically occurs when the WebDriver tries to perform actions or operations immediately after closing the driver session. Let’s dive into a detailed explanation of this scenario:

WebDriver Session

In Selenium, a WebDriver session is established when we create an instance of the WebDriver for a specific web browser. This session is a bridge between the test script and the web browser. It allows us to control and automate interactions with the web elements on the page.

Closing the WebDriver Session

Once the test execution is complete, it’s mandatory to close the WebDriver session properly to release resources and terminate the browser.

Selenium provides two methods to close the session:

  • driver.close(): This method closes the current browser window or tab but leaves the WebDriver session active. This is often used when multiple browser windows or tabs are open.

  • driver.quit(): This method closes the entire WebDriver session, terminating the browser instance and releasing all associated resources. This method is used at the end of the test suite when we no longer need the WebDriver.

The Exception Scenario

When the test script tries to interact with the WebDriver to find elements, click buttons or navigate to URLs after the WebDriver session has been closed. TheWebDriverException is thrown. The purpose of this exception is to safeguard against trying to perform operations on a WebDriver that is no longer valid or operational.

For example, if you call driver.findElement(By.id(“elementId”)) after driver.quit() has been invoked, then a WebDriverException will be raised. The reason is because the WebDriver session has already been closed.

Let us understand this exception with an example.
from selenium import webdriver

# Initialize the WebDriver and open a web page
driver = webdriver.Chrome()
driver.get("https://example.com")

# Perform some actions on the web page
element = driver.find_element_by_css_selector("a.example-link")
element.click()

# Close the WebDriver session
driver.quit()

# Attempt to interact with the WebDriver after closing the session
try:
  # This line will raise a WebDriverException
  driver.get("https://anotherwebsite.com")

except Exception as e:
  print(f"Caught an exception: {type(e).__name__}: {str(e)}")

In this example, these steps are followed:

  1. The first step is to initialize the WebDriver using Chrome and then navigate to the website’s URL.
  2. Perform a click action on the page.
  3. After completing the click action, close the WebDriver session using driver.quit().
  4. Call driver.get() method and then attempt to interact with the WebDriver. WebDriverException is thrown because the WebDriver session is already closed.

Resolving WebDriverException

The resolution for WebDriverException involves proper session management in our Selenium automation scripts. Let us see the steps to resolve this exception.

  • Perform actions before closing the session: Before closing the WebDriver session, make sure all necessary actions, interactions, and validations are completed in the script. This means all the test steps should be executed before we quit the WebDriver.

  • Close WebDriver at suite level (using TestNG): While using TestNG in the automation framework, close the WebDriver session at the suite level using the “@AfterSuite” annotation. This annotation ensures that the WebDriver session is successfully closed after all the tests within the suite are executed.
    import org.testng.annotations.AfterSuite;
    import org.testng.annotations.BeforeSuite;
    
    public class YourTestSuite {
    	@BeforeSuite
    	public void setUp() {
    		// Initialize WebDriver and set up your test environment
    	}
    
    	@AfterSuite
    	public void tearDown() {
    		// Close the WebDriver session after all tests in the suite have completed
    		driver.quit();
    	}
    }
  • Use proper exception handling: Catch and log any exceptions that might occur during test execution by using exception handling. This helps in identifying issues and debugging them smoothly and keeps the test execution going.

AI and Test Automation: The Smart Shift

Though Selenium is one of the oldest legacy automation tools, there are many drawbacks associated with it. For a company that wants to set up a testing automation framework and start testing quickly, Selenium won’t be helping it. While using Selenium, we need to begin creating the framework from scratch. Integrate the reports, the data flow, and all other required integrations, cumulating to huge cost, time, and effort.

Again, scripting is another headache, as the tester needs to be technically brilliant to create, debug, and maintain test scripts as the testing progresses. All these make Selenium more complex and less preferred. Read here the 11 reasons why not to use Selenium for test automation.

Today, it is an era of codeless automation tools, and testRigor is one of the leading players. testRigor, with its integrated generative AI, offers a multitude of features, a few of them are:

  • When using testRigor, you don’t have to wait for the page to load or add explicit wait conditions. As testrigor, by default, will wait for the page to load and then only execute the test steps. Hence, there are no exceptions caused due to incorrect wait conditions.

  • testRigor helps to create test scripts in plain English, so your team does not have to be proficient in programming languages. Also, with testRigor, manual testers can create test scripts faster than automation testers with other tools like Selenium.

    Everyone in your team can write and execute test cases with testRigor irrespective of their technical background.

  • Another advantage of testRigor is it doesn’t rely on flaky XPath or CSS selectors; instead, it uses its own stable way of identifying elements, i.e., testRigor locators. This process has become more straightforward and human, thanks to AI algorithms. You just mention the UI text that you see on the screen or its position to identify the element, such as:
    click "cart"
    click on button "Delete" below "Section Name"

Conclusion

The current market strategy is to release more frequently, with new features maintaining the product quality. So, to be in sync with this strategy, QA needs a powerful and intelligent test automation tool to ease testers’ tasks. Selenium is failing to meet the current trends where speed and quality should walk in tandem.

testRigor is like a plug-and-play test automation tool, and no additional setup is required other than creating an account. testRigor’s AI-powered intelligent capabilities let you meet your test automation goals easily, quickly, and within your budget.

Sign up for a free trial to discover its powerful features.

You're 15 Minutes Away From Automated Test Maintenance and Fewer Bugs in Production
Simply fill out your information and create your first test suite in seconds, with AI to help you do it easily and quickly.
Achieve More Than 90% Test Automation
Step by Step Walkthroughs and Help
14 Day Free Trial, Cancel Anytime
“We spent so much time on maintenance when using Selenium, and we spend nearly zero time with maintenance using testRigor.”
Keith Powe VP Of Engineering - IDT
Related Articles

SAP Concur Testing

Concur Technologies, now SAP Concur, is an American software-as-a-service (SaaS) company providing travel and expense management ...

Authorize.net Testing

You need a payment gateway in several scenarios, especially when you are running a business that requires secure, efficient, and ...

KYC Portal CLM Testing

KYC Portal CLM is an award-winning Client Lifecycle Management (CLM) platform designed to streamline and automate the Know Your ...
On our website, we utilize cookies to ensure that your browsing experience is tailored to your preferences and needs. By clicking "Accept," you agree to the use of all cookies. Learn more.
Cookie settings
Privacy Overview
This site utilizes cookies to enhance your browsing experience. Among these, essential cookies are stored on your browser as they are necessary for ...
Read more
Strictly Necessary CookiesAlways Enabled
Essential cookies are crucial for the proper functioning and security of the website.
Non-NecessaryEnabled
Cookies that are not essential for the website's functionality but are employed to gather additional data. You can choose to opt out by using this toggle switch. These cookies gather data for analytics and performance tracking purposes.