Chuyển tới nội dung
Home » Try Except Selenium Python | Test Your Web Or Mobile Apps On 3000+ Browsers

Try Except Selenium Python | Test Your Web Or Mobile Apps On 3000+ Browsers

NoSuchElementException in Python Selenium - How to handle it and troubleshoot

How to ignore a particular exception and replace it with custom output in python

I possess a script that automatically logs me into a website. In order to reach the first thread, I must repeatedly click on the load more button ( button repeatedly ). However, when I reach the end of the page, Selenium throws an error because the load more button becomes unavailable once the starting point is reached.

Among the errors that I want to avoid, there is one specific error that I prefer to ignore and simply display the message “Reached initial thread “. My initial plan was to execute the following action:


class ReachedEndException(Exception): pass try: do_somethong() except ReachedEndException: print "Reached initial thread"

am i heading in the right direction or is there a more optimal approach for accomplishing this?

A functional illustration in accordance with Konstantin’s response.


try: while True: dr.find_element_by_xpath("//li[@class='more-pages']/a[1]").click() sleep(2) except NoSuchElementException: print "Reached Initial Thread."

Taken from the Selenium docs

Solution:

You’re heading in the right direction, but you need to identify the correct error. Keep in mind that you can identify any type of error, whether it is a built-in error, a user-defined error, or an error from an external library. You just need to identify the specific error that Selenium is raising and handle it appropriately.

In Python programming, exception handling allows a programmer to enable flow control. And it has no. of built-in exceptions to catch errors in case your code breaks. Using try-except is the most common and natural way of handling unexpected errors along with many more exception-handling constructs. In this tutorial, you’ll get to explore some of the best techniques for using try-except in Python.

Error Handling or Exception Handling in Python can be enforced by setting up exceptions. Using a try block, you can implement an exception and handle the error inside an except block. Whenever the code breaks inside a try block, the regular code flow will stop and the control will get switched to the except block for handling the error.

Handling Exception using SeleniumBase

In the code below, we will try to find a product and if the product cannot be found then we will assert for the “not found” text instead –

from page_objects.shop_page import ShopPage from selenium.common.exceptions import NoSuchElementException class ShopTest(ShopPage): def test_search_products(self): # open page self.open_page() # search for product self.send_keys(self.search_input, “Toys”) self.click(self.search_btn) # assert product image try: self.assert_element(self.product_img) except NoSuchElementException: self.assert_text(“No products were found matching your selection.”, self.no_products_txt)

When the exception was thrown after the product was not found, we handled it using the

try/except

block. Similarly, you can handle such exceptions for any of your use cases and perform some other action instead.

Check out the video below to learn more about handling exceptions using the SeleniumBase framework –

To learn more about Selenium Python, check out the full tutorial series here for free!

I hope this post helped you out, let me know if you have any questions in the comments below!

Happy testing!

Implementing try/catch in Python’s Selenium to verify the non-existence of an element

Feedback

To catch all exceptions, use the appropriate syntax. “Exception” is the top-level class in the exception hierarchy and handles all program errors (excluding system errors). Refer to Section 8: Errors and Exceptions in the python tutorial for more information.

  • How to use try/catch with selenium python to check the absence of an element?
  • How do I catch all of these exceptions in python?
  • Checking for javascript exceptions with selenium?
  • How to ignore a particular exception and replace it with custom output in python
  • What are exceptions in selenium Python?
  • How to deal with exceptions in Python?
  • Is it possible to have multiple except statements in Python?
  • Should I keep a namespace for selenium exceptions?
NoSuchElementException in Python Selenium - How to handle it and troubleshoot
NoSuchElementException in Python Selenium – How to handle it and troubleshoot

Handling Errors and Exceptions on the Cloud Selenium Grid

Now that we have covered the essentials to get started with Python web automation in Selenium, we will look at handling errors and exceptions in Selenium Python on a cloud grid. In this instance, we are using LambdaTest.

LambdaTest is a cloud-based cross browser testing platform that allows you to perform Python automation testing at scale over a cloud Selenium Grid. The unique and fully featured platform offers an online browser farm of 3000+ real browsers across multiple operating systems; thus helping businesses deliver more quality software at a more rapid speed.

You can also Subscribe to the LambdaTest YouTube Channel and stay updated with the latest tutorials around automated browser testing, Selenium testing, Cypress E2E testing, CI/CD, and more.

To get started with LambdaTest, please follow the below-mentioned steps:

  1. Register and log in to your LambdaTest account.
  2. Move to the LambdaTest Profile Section and copy your username and access key, which will be used to access the Remote Selenium Grid of LambdaTest.
  3. You will also need the desired capabilities generated using the LambdaTest Capabilities Generator. You can generate the capabilities needed for the specific test you are carrying out on that page.

We have listed the different types of exceptions in Selenium Python in the blog. Now, we will dig deeper into two common exceptions in Selenium Python when performing automated tests.

NoSuchElementException

A NoSuchElementException is thrown if we attempt to locate any element unavailable on the page (or the DOM).

Scenario 1 (Chrome Browser)

  1. Go to the URL link https://www.lambdatest.com/selenium-playground/.
  2. Locate an element called “p-10” by its name.
  3. Click on the element.

Scenario 2 (Firefox Browser)

  1. Go to the URL link https://www.lambdatest.com/selenium-playground/.
  2. Locate an element called “level-up” by its name.
  3. Click on the element.

Implementation (Scenario 1 on the Chrome Browser):

Implementation (Scenario 2 on the Firefox Browser):

Code Execution:

We run the two test scripts using parallel testing, which allows the execution of the same tests simultaneously. To run the test, type the following command in the terminal.

poetry run pytest seltests/test_nosuchelement_google.py seltests/test_nosuchelement_firefox.py -n 2

The terminal shows that the test execution failed.

In the LambdaTest Builds dashboard, the failed test executions are displayed.

Code Walkthrough:

We are conducting a joint code walkthrough because the imported Selenium Python libraries used in both test scenarios are identical.

Step 1: Import the necessary Selenium Python classes – pytest, webdriver, sys, By, NoSuchElementException.

import pytest

from selenium import webdriver

import sys

from selenium.webdriver.common.by import By

from selenium.common.exceptions import NoSuchElementException

We imported pytest, primarily used for unit testing in Selenium Python. Selenium WebDriver is a web framework that enables us to perform cross-browser testing, and in this case, we are using Python to write the test scripts. The By query is based on the find_element() method in Selenium that targets a specific locator.

Step 2: We specify the browser capabilities based on the browser we use to conduct the automated tests in LambdaTest. They are generated using the LambdaTest Capabilities Generator.

10

11

ch_capabilities = {

‘LT:Options’ : {

“user” : ”

“,

“accessKey” : ”

“,

“build” : “NoSuchElementException Test on Chrome”,

“name” : “NoSuchElementException Test on Chrome”,

“platformName” : “Windows 10”

},

“browserName” : “Chrome”,

“browserVersion” : “102.0”,

10

11

ff_capabilities = {

‘LT:Options’ : {

“user” : ”

“,

“accessKey” : ”

“,

“build” : “NoSuchElementException Test for LambdaTest (Firefox)”,

“name” : “NoSuchElementException Test for LambdaTest (Firefox)”,

“platformName” : “Windows 10”

},

“browserName” : “Firefox”,

“browserVersion” : “101.0”,

Step 3: We define a function that starts with “test” in which we assign the test methods. You can learn more about it through this blog on Pytest testing using Selenium WebDriver.

def test_lambdatest_nosuchelement():

Step 4: We then set our LambdaTest username and accesskey to variables we appended to remote_url. This remote URL connects us to the Remote Selenium Grid (@hub.lambdatest.com/wd/hub).

# LambdaTest Profile username

user_name = ”

# LambdaTest Profile access_key

app_key = ”

# Remote Url to connect to our instance of LambdaTest

remote_url = “https://” + user_name + “:” + app_key + “@hub.lambdatest.com/wd/hub”

Step 5: We then use the remote_url and browser capabilities to instantiate the corresponding browser (i.e. Chrome or Firefox)

ch_driver = webdriver.Remote(

command_executor=remote_url, desired_capabilities = ch_capabilities)

ff_driver = webdriver.Remote(

command_executor=remote_url, desired_capabilities = ff_capabilities)

Step 6: We then get the URL of the website on which we want to locate a specific element. In our test, we try to locate an element by its name and click on it. Once the element had been located and clicked, we quit the test.

ch_driver.get(‘https://www.lambdatest.com/selenium-playground/’)

ch_driver.maximize_window()

# Will find an element by its NAME property in the page and click it

ch_driver.find_element(By.CLASS_NAME, “p-10”).click()

ch_driver.quit()

ff_driver.get(‘https://www.lambdatest.com/selenium-playground/’)

# This will maximize the window interface of the driver class in this case it’s FIREFOX

ff_driver.maximize_window()

# Will find an element by its NAME property in the page and click it

ff_driver.find_element(By.CLASS_NAME, “p-10”).click()

ff_driver.quit()

Watch this video to learn exception handling in Selenium, which covers different types of exceptions and how to handle them using various methods.

NoSuchElementException Handling in Action

According to the exception mentioned above, we must catch “NoSuchElementException” and print the proper log messages to guarantee that our test fails with the proper error message.

We use the try and except method to catch the exception when it is raised in the test script. The “try” block lets you check the code for errors, while the “except” block lets you handle the errors or exceptions raised.

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

import pytest

from selenium import webdriver

import sys

from selenium.webdriver.common.by import By

from selenium.common.exceptions import NoSuchElementException

ch_capabilities = {

‘LT:Options’ : {

“user” : ”

“,

“accessKey” : ”

“,

“build” : “NoSuchElementException Test on Chrome”,

“name” : “NoSuchElementException Test on Chrome”,

“platformName” : “Windows 10”

},

“browserName” : “Chrome”,

“browserVersion” : “102.0”,

def test_lambdatest_nosuchelement():

# LambdaTest Profile username

user_name = ”

# LambdaTest Profile access_key

app_key = ”

# Remote Url to connect to our instance of LambdaTest

remote_url = “https://” + user_name + “:” + app_key + “@hub.lambdatest.com/wd/hub”

ch_driver = webdriver.Remote(

command_executor=remote_url, desired_capabilities = ch_capabilities)

ch_driver.get(‘https://www.lambdatest.com/selenium-playground/’)

ch_driver.maximize_window()

try:

# ‘By’ is used to locate the element by its property

ch_driver.find_element(By.CLASS_NAME, “p-10”)

ch_driver.click()

except NoSuchElementException:

print(“Exception Handled”)

ch_driver.quit()

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

import pytest

from selenium import webdriver

import sys

from selenium.webdriver.common.by import By

from selenium.common.exceptions import NoSuchElementException

# Desired Capabilities according to SELENIUM 4

ff_capabilities = {

‘LT:Options’ : {

“user” : ”

“,

“accessKey” : ”

“,

“build” : “NoSuchElementException Test for LambdaTest (Firefox)”,

“name” : “NoSuchElementException Test for LambdaTest (Firefox)”,

“platformName” : “Windows 10”

},

“browserName” : “Firefox”,

“browserVersion” : “101.0”,

def test_lambdatest_nosuchelement():

# LambdaTest Profile username

user_name = ”

# LambdaTest Profile access_key

app_key = ”

# Remote Url to connect to our instance of LambdaTest

remote_url = “https://” + user_name + “:” + app_key + “@hub.lambdatest.com/wd/hub”

# creating an instance of Firefox based on the remote url and the desired capabilities

ff_driver = webdriver.Remote(

command_executor=remote_url, desired_capabilities = ff_capabilities)

ff_driver.get(‘https://www.lambdatest.com/selenium-playground/’)

# This will maximize the window interface of the driver class in this case it’s FIREFOX

ff_driver.maximize_window()

try:

# Will find an element by its NAME property in the page and click it

ff_driver.find_element(By.CLASS_NAME, “p-10”).click()

except NoSuchElementException:

print(“Exception Handled”)

ff_driver.quit()

Execution:

Use the terminal to enter the following command to perform Selenium Python testing in parallel on the LambdaTest Grid.

poetry run pytest seltests/test_handle_nosuchelement_google.py

seltests/test_handle_nosuchelement_firefox.py -n 2

The tests will be executed successfully.

The passed tests will be shown as follows in the LambdaTest Dashboard.

The passed tests will be shown as follows in the LambdaTest Dashboard.

Code Walkthrough:

The “try” block will run the find_element() argument and take in the By query to locate an element using its name in the URL provided.

Step 1: In the browser’s inspect tool, click on Console and type the following command to find the element with the name “p-10”.

$x (“//*[text()=’p-10′]”)

The test does not fail since the element with the name “p-10” does not exist. The “except” block will run, catching the exception.

Step 2: The try and except code block is the same in Chrome and Firefox text scripts.

StaleElementReferenceException

This exception is raised whenever an element is not present in the DOM or is deleted.

Scenario 1 (Chrome Browser)

  1. Go to the URL link https://ecommerce-playground.lambdatest.io/index.php?route=account/login.
  2. Find the reference to the email and password text fields.
  3. Click on a link that reloads the entire web page.
  4. Enter the password into the password field with the reference we located before the web page reloaded.

Scenario 2 (Firefox Browser)

  1. Go to the URL link https://ecommerce-playground.lambdatest.io/index.php?route=account/login.
  2. Find the reference to the email and password text fields.
  3. Click on a link that reloads the entire web page.
  4. Enter the password into the password field with the reference we located before the web page reloaded.

Implementation (Scenario 1 on the Chrome Browser):

Implementation (Scenario 2 on the Firefox Browser):

Execution:

Run the following command in the terminal to execute the test scripts in parallel testing.

poetry run pytest seltests/test_staleelement_google.py seltests/test_staleelement_firefox.py

We receive a StaleElementExceptionError message in the terminal.

We can view the raised exceptions in the LambdaTest Dashboard.

Run Python test scripts across 3000+ devices & browsers. Try LambdaTest Now!

Code Walkthrough:

Step 1: Import the necessary Selenium Python classes – pytest, webdriver, sys, By, and StaleElementReferenceException.

import pytest

from selenium import webdriver

import sys

from selenium.webdriver.common.by import By

from selenium.common.exceptions import StaleElementReferenceException

Step 2: We generate capabilities in the LambdaTest Capabilities based on the browser and OS.

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

ch_capabilities = {

‘LT:Options’: {

“user”: ”

“,

“accessKey”: ”

“,

“build”: “StaleElementReferenceException Test on Chrome”,

“name”: “StaleElementReferenceException Test on Chrome”,

“platformName”: “Windows 10”

},

“browserName”: “Chrome”,

“browserVersion”: “102.0”,



Firefox

ff_capabilities = {

‘LT:Options’ : {

“user” : ”

“,

“accessKey” : ”

“,

“build” : “StaleElementReferenceException Test for LambdaTest (Firefox)”,

“name” : “StaleElementReferenceException Test for LambdaTest (Firefox)”,

“platformName” : “Windows 10”

},

“browserName” : “Firefox”,

“browserVersion” : “101.0”,

Step 3: We create a function that will contain our test methods. In the function, we define the username and password for a remote_url that will connect to the Remote Selenium Grid.

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

def test_ecommerceplayground_staleelement():

# LambdaTest Profile username

user_name = ”

# LambdaTest Profile access_key

app_key = ”

# Remote Url to connect to our instance of LambdaTest

remote_url = “https://” + user_name + “:” + \

app_key + “@hub.lambdatest.com/wd/hub”

# creating an instance of Chrome based on the remote url and the desired capabilities

ch_driver = webdriver.Remote(

command_executor=remote_url, desired_capabilities=ch_capabilities)

ch_driver.get(

‘https://ecommerce-playground.lambdatest.io/index.php?route=account/login’)

emailElement = ch_driver.find_element(By.ID, “input-email”)

passwordElement = ch_driver.find_element(By.ID, “input-password”)

emailElement.send_keys(“[email protected]”)

ch_driver.find_element(By.XPATH, “//input[@type=’submit’]”).click()

passwordElement.send_keys(“password”)

ch_driver.quit()

The code for the browser tests is the same. We set the Chrome webdriver to ch_driver while the Firefox webdriver is ff_driver. Based on their ids, the emailElement variable will locate the email input element, while the passwordElement variable will locate the input element.

We then enter an email into the email input using the emailElement.send_keys() function and locate and click the login button, which is the type “submit”. Then enter the password and finally quit the test with the .quit() function.

When the code is run, a StaleElementReferenceException will be raised for the following reasons:

  • In Chrome, the element is not attached to the page document.
  • In Firefox, the element reference password is no longer attached to the DOM.

Code Walkthrough:

We apply the try and except code blocks to handle the “StaleElementReferenceException” when it is thrown during our test’s execution.

The try block will run the code to add the password in which the exception will be raised. The except block will handle the exception by locating the password input element and sending the password value.

When the code is run, it will execute successfully in the terminal.

poetry run pytest seltests/test_handle_staleelement_google.py seltests/test_handle_staleelement_firefox.py

We can see successful test executions in the LambdaTest Build dashboard.

For a complete view of all test results and trends, check out your LambdaTest Analytics Dashboard. It lets you see how the tests are moving along, so you can make sure that everything is executed accordingly.

Exception handling Scenarios

All the examples shown below requires your code to be inserted wherever appropriate.The examples just address ideas on exception scenarios and how they can be handled.

1.NoSuchElementException

Common exception encountered when the inspected element is missing.Let us say we are looking at a tweet in twitter to check if that specific tweet has any replies.We may run into a situation where a tweet may not have an error and hence the element is not available.In this example I just append a value of none if I encounter a NoSuchElementException.

2.TimeoutException

This exception is not a very common one but nonetheless very useful to capture timeout errors.The webpage might take more time to load than normal which usually happens when some websites are too slow or they are overloaded.Use this exception with caution as it may end up adding unnecessary execution time if you are testing any stable websites.

ElementClickInterceptedException

This exception is thrown when the element you try to click an element but it gets blocked by another element and becomes unclickable.The common cause most of the time is due to a pop-up being triggered or some actions that require interaction.This can be handled by simply closing the pop up or through a javascript executor.

I hope this blog has got you started to think about exceptions and how to handle them without compromising on execution time and speed.Hopefully you will never meet an exception!Happy Testing.

In this post, we will take a look at how to do exception handling using Selenium Python and the SeleniumBase framework. So, before we see how we can do that let’s talk about why you need to handle exceptions in the first place, usually if there’s an error within your test you would want the test to fail and that is true for 95% of the scenarios.

But, you will run into certain scenarios where you will encounter an error and you would want to handle that differently instead of just throwing the error and failing your test.

For example –

  • If you are trying to find an element and if that element is not there, you want to perform some other action instead
  • Or, if you want to click a button but if that click doesn’t work you might want to perform some sort of retry functionality
Python Tutorial: Using Try/Except Blocks for Error Handling
Python Tutorial: Using Try/Except Blocks for Error Handling

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free

Exceptions – Selenium Python

Exceptions in Selenium Python are the errors that occur when one of method fails or an unexpected event occurs. All instances in Python must be instances of a class that derives from BaseException. Two exception classes that are not related via subclassing are never equivalent, even if they have the same name. The built-in exceptions can be generated by the interpreter or built-in functions. This article revolves around multiple exceptions that can occur during the run of a Selenium program.

Summary – How to Best Use Try-Except in Python

while programming, errors are bound to happen. It’s a fact that no one can ignore. And, there could be many reasons for errors like bad user input, insufficient file permission, the unavailability of a network resource, insufficient memory, or most likely the programmer’s mistake.

Anyways, all of this can be handled if your code uses exception handling and implements it with constructs like try-except, tr-except-else, and try-except-finally. Hope, you would have enjoyed reading the above tutorial.

If you liked the post, then please don’t miss to share it with friends and on your social media accounts.

Best,TechBeamers.

Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are the problems in a program due to which the program will stop the execution. On the other hand, exceptions are raised when some internal events occur which changes the normal flow of the program.Note: For more information, refer to Errors and Exceptions in PythonSome of the common Exception Errors are :

  • IOError: if the file can’t be opened
  • KeyboardInterrupt: when an unrequired key is pressed by the user
  • ValueError: when the built-in function receives a wrong argument
  • EOFError: if End-Of-File is hit without reading any data
  • ImportError: if it is unable to find the module
Exception Handling in Python | TRY EXCEPT in Python | Python Tutorial for Beginners #8
Exception Handling in Python | TRY EXCEPT in Python | Python Tutorial for Beginners #8

Common Exceptions in Selenium WebDriver

  1. TimeoutException: Thrown when there is not enough time for a command to complete.

  2. UnableToCreateProfileException: You can open a browser with specific options using profiles, but sometimes a new version of Selenium Driverserver or browser may not support the profiles.

  3. UnableToSetCookieException: This occurs if a driver is unable to set a cookie.

  4. UnexpectedAlertPresentException: This Selenium exception happens when there is the appearance of an unexpected alert.

  5. UnexpectedTagNameException: Happens if a support class did not get a web element as expected.

  6. InvalidCookieDomainException: This happens when you try to add a cookie under a different domain rather than the current URL.

  7. InvalidCoordinatesException: This happens if the coordinates offered to an interacting operation are not valid.

  8. InvalidElementStateException: This Selenium exception occurs if a command cannot finish as the element is invalid.

  9. InvalidSessionIdException: Takes place when the given session ID does not include in the list of active sessions, which means the session does not exist or is inactive either.

  10. InvalidSwitchToTargetException: Happens if a frame or window target to switch does not exist.

  11. ElementClickInterceptedException: The command could not complete as the element receiving the events is concealing the element which was requested clicked.

  12. ElementNotInteractableException: This Selenium exception gets thrown when an element is present in the DOM, but it is impossible to interact with such an element.

  13. NoAlertPresentException: Happens when you switch to no presented alert.

  14. NoSuchAttributeException: This occurs when we can’t find the attribute of the element.

  15. NoSuchContextException: Happens in mobile device testing and is thrown by ContextAware.

  16. NoSuchCookieException: This exception gets thrown if there is no cookie matching with the given pathname found amongst the associated cookies of the current browsing context’s active document.

  17. NoSuchElementException: Happens if we can’t find an element.

  18. NoSuchFrameException: Takes place if frame target to be switch does not exist.

  19. NoSuchWindowException: This occurs if the window target to be switch does not exist.

  20. NotFoundException: This exception is a subclass of WebDriverException. It happens when an element on the DOM doesn’t exist.

How to use try/catch with selenium python to check the absence of an element?

To continue with downstream code, I must refresh the page when the element is not present and proceed when it eventually appears. Here is my code:


Button=False while not Button: try: Btn = addButton = browser.find_element_by_class_name("my button") print("Button isn't there") time.sleep(1) browser.refresh() except: Btn = addButton = browser.find_element_by_class_name("my button") print("Button was clicked") Btn.click() Button = True

The “try” part should be modified to verify the absence of the “my button” in order to continue refreshing the page.

Solution 1:

If we were to convert this code into everyday language, it could be represented as something akin to this.

If the button is absent, it is considered an error. In the event of an error, it is assumed that the button was present and it should be clicked. If no errors occur, keep refreshing the page until the button becomes visible.

The presence of the button on the page should not be considered an error, but rather an anticipated behavior. Therefore, there is no need to employ a try-except block to manage this behavior.

Polling for page elements using Selenium is a non-idiomatic and significant anti-pattern that should be avoided. Instead, opt for timeouts and objects like

wait

to handle this task.

Here is an example:


from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions from selenium.common.exceptions import ElementNotVisibleException, ElementNotSelectableException driver = webdriver.Firefox() # or chrome... fluent_wait = WebDriverWait(driver, 10, poll_frequency=1, ignored_exceptions=[ElementNotVisibleException, ElementNotSelectableException]) elem = wait.until(EC.element_to_be_clickable((By.XPATH, "x_path_to_the_button"))) if not elem: print("Button isn't there") driver.refresh() else: print("Button was clicked") elem.click()

Solution 2:


While True: try: time.sleep(1) Btn = browser.find_element_by_class_name("my button") Btn.click() break except: print("Button isn't there") browser.refresh()

Ensure the presence of the btn and click it if it’s not there, otherwise simply refresh the page. However, a more efficient approach would be to utilize Webdriver waits. Refer to Z4-tier’s response above for the correct usage of Selenium.

Lập trình Python  - 35. Cách sử dụng Try Except
Lập trình Python – 35. Cách sử dụng Try Except

Introduction to Errors and Exceptions in Selenium Python

A developer must create code that thoroughly tests every component of an application or program’s operation before it can run. The code’s instructions, meanwhile, occasionally fail to work as planned.

The same principle applies to QA engineers when they write code to test the features and functioning of developed applications in order to make sure they are prepared for production and to be released to users.

Here is an analogy to help you better understand errors and exceptions in Selenium Python.

Imagine you have a work meeting on Zoom or any online video conference application while at home. During the meeting, the electricity was cut off, which is reported to have affected the whole city. You have no choice but to call off the meeting and wait for the electricity to be reinstated. Akin to this, errors are raised during runtime, and rectifying them is nearly impossible.

In contrast, exceptions are events that raise interruptions while an application runs and can be rectified using exception handling.

Exceptions in Selenium Python are generally classified into two types.

  • Checked Exceptions
  • Unchecked Exceptions

Checked Exception handling in Selenium is conducted while writing the code. On the other hand, Unchecked Exceptions are raised during runtime and can generate fatal errors compared to the former type of exception.

You can quickly sharpen your knowledge of exceptions in Selenium Python by reading through this detailed blog on different exceptions in Selenium.

Performing Selenium automated browser testing differs across the ecosystem in which the tests are being carried out. The test scripts may differ depending on the operating systems, browsers, or programming languages they are written in. Therefore, the raised errors andexceptions in Selenium Python may be different. For example, if the browsers don’t have the specified element, Selenium testing of an element property in web browsers may raise exceptions like NoSuchElementException.

To ensure that the applications function correctly and obstruct users’ interactions with the finished product, it is advised that Selenium error and exception handling be used as a standard practice.

Python3


def


divide(x, y):


try


result


print


"Yeah ! Your answer is :"


, result)


except


ZeroDivisionError:


print


"Sorry ! You are dividing by zero "


divide(

Auxiliary Space: O(1)

Output :

Yeah ! Your answer is : 1

Code 1: There is an exception so only except clause will run.

Advanced Exception Handling in Python
Advanced Exception Handling in Python

Python3


try


print


(k)


except


ZeroDivisionError:


print


"Can't divide by zero"


finally


print


'This is always executed'

Output:

Can’t divide by zero
This is always executed

Related Articles:

Don’t miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.

Dive into the future of technology – explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.

Last Updated :
13 Apr, 2023

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment…

Selenium is a very versatile web scraping tool that is accessible via multiple programming languages.

It’s distinguished from text-parsing scrapers like BeautifulSoup as it actually simulates a web navigation experience, enabling you to scrape website running on a lot of Javascript and iframes.

That makes Selenium especially powerful when you are in need of scraping large websites, like e-commerce sites.

However, as with large websites, the pages you scrape won’t be totally identical with one another.

Hence, error or exception handling is very, very important.

Without proper exception handling, you may face errors after errors and waste time, as any error will simply halt your scraping work.

This is especially bad when you have set up your scraping task to take place over lunch or overnight.

Sometimes, certain pages do not have a certain element, which is very common.

For example, you might be scraping Amazon for products’ reviews. Some products that do not have any reviews simply do not have any review element to show you.

This can be easily solved by appending a “” or None to the list that you’re populating your scrape result.


from selenium.common.exceptions import NoSuchElementException reviews = [] for page in pages_to_scrape: try: # Insert your scraping action here reviews.append(driver.find_element_by_css_selector('div.review').text) except NoSuchElementException: # Just append a None or "" reviews.append(None)

Some websites are simply slow or too small that your scraping has caused their server to overload.

The latter is always bad and you shouldn’t crash other people’s websites when scraping.

In any case, timeouts (i.e. page failed to load) are common on large websites.

However, I won’t recommend catching this error unless you know from experience that the website is prone to timeouts. It can be a huge waste of resource if the website has a 0.01% chance of timeout.


from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException driver.get("your url") # Remove the while loop and break if you don't want to try again when it took too long while True: try: # Define an element that you can start scraping when it appears # If the element appears after 5 seconds, break the loop and continue WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.CSS_SELECTOR, "your selector"))) break except TimeoutException: # If the loading took too long, print message and try again print("Loading took too much time!")

This error happens when the element you try to click (e.g. the “next page” button) gets blocked by another element and becomes unclickable.

The common cause of this is a pop-up being triggered, or there is a chat box that appears at the bottom-right of the page.

There are a few ways to solve this. The first way is to close the pop-up.


from selenium.common.exceptions import ElementClickInterceptedException try: # Tries to click an element driver.find_element_by_css_selector("button selector").click() except ElementClickInterceptedException: # If pop-up overlay appears, click the X button to close time.sleep(2) # Sometimes the pop-up takes time to load driver.find_element_by_css_selector("close button selector").click()

You may also use Javascript to hide that element (credit to Louis’ StackOverflow answer):


from selenium.common.exceptions import ElementClickInterceptedException try: # Tries to click an element driver.find_element_by_css_selector("button selector").click() except ElementClickInterceptedException: element = driver.find_element_by_class_name("blocking element's class") driver.execute_script(""" var element = arguments[0]; element.parentNode.removeChild(element); """, element)

If it’s not a pop-up, the problem could be solved by scrolling away, hoping that the blocking element moves with you and away from the button/link to be clicked.


from selenium.common.exceptions import ElementClickInterceptedException try: # Tries to click an element driver.find_element_by_css_selector("button selector").click() except ElementClickInterceptedException: # Use Javascript to scroll down to bottom of page driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

Stale element happens when the element is was deleted or no longer attached to the DOM.

Though a not very common error, some websites are prone to having this error.

When encountered with this error, you can just try again for a number of times.


from selenium.common.exceptions import StaleElementReferenceException while True: try: item_list.append(driver.find_element_by_id("item id").text) except StaleElementReferenceException: continue # If StaleElement appears, try again break # once try is successful, stop while loop

Catching errors and using these exceptions slows your code down significantly. It can cause a regular 1-hour scraping task to double in time especially if you wrap all your scraping actions with error exceptions.

Sometimes it’s totally inescapable, and that’s when a full coverage of error exceptions is necessary so that you can run it overnight without any worries.

However, I recommend to do a trial and error on your code and implement error exceptions only when you encounter them.

Start with a small, representative sample of your web pages to find out the type of errors that can happen.

If you’re scraping a few elements in a row, it’s best to assign the result of the scrape to a temporary, placeholder variable before appending to a list.

This is because if you’re appending all to their respective lists, an error in the later stages will cause your prior appended lists having more elements.


# ==================== # Use this way # ==================== try: item_one_temp = driver.find_element_by_id("item one id").text item_two_temp = driver.find_element_by_id("item two id").text item_one.append(item_one_temp) item_two.append(item_two_temp) except NoSuchElementException: item_one.append(None) item_two.append(None) # ==================== # Instead of this # ==================== try: item_one.append(driver.find_element_by_id("item one id").text) # if the next element does not exist, item_one list is already appended # i.e. one of your list is longer than another item_two.append(driver.find_element_by_id("item two id").text) except NoSuchElementException: item_one.append(None) item_two.append(None)

It’s useful to specify specific errors that you expect as different errors require different treatments.

Only use a broad “except” statements if you’re planning to do the same if any error arises.

I wish that I know all this before I started scraping as I had to waste a lot of time on StackOverflow. Hope this guide has been useful 🙂

Like the post? Consider donating to fund the maintenance of this website:

Python3


def


AbyB(a , b):


try


((a


b)


(a


b))


except


ZeroDivisionError:


print


"a/b result in 0"


else


print


(c)


AbyB(


2.0


3.0


AbyB(


3.0


3.0

Output:

-5.0
a/b result in 0

Finally Keyword in Python

Python provides a keyword finally, which is always executed after the try and except blocks. The final block always executes after the normal termination of the try block or after the try block terminates due to some exceptions.

Syntax:

try:
# Some Code
except:
# Executed if error in the
# try block
else:
# execute if no exception
finally:
# Some code …..(always executed)

Code:

Python Programming Tutorial #18 - Try and Except (Python Error Handling)
Python Programming Tutorial #18 – Try and Except (Python Error Handling)

How to use try-except and try-except-else in Python?

Why use the try-except or try-except-else clause?

With the help of try-except and try-except-else, you can avoid many unknown problems that could arise from your code. For example, the Python code using the LBYL (Look before you leap) style can lead to race conditions. Here, the try-except clause can come to rescue you. Also, there are cases where your code depends critically on some information that could get outdated by the time you receive it. For example, the code making calls to os.path.exists or Queue. full may fail as these functions might return data that becomes stale by the time you use it. The wiser choice here would be to follow the try-except-else style in your code to manage the above cases more reliably.

Raising exceptions is also permissible in Python. It means you can throw or raise an exception whenever it is needed. You can do it simply by calling [raise Exception(‘Test error!’)] from your code. Once raised, the exception will stop the current execution as usual and will go further up in the call stack until handled.

Why use Exceptions? They not only help solve popular problems like race conditions but are also very useful in controlling errors in areas like loops, file handling, database communication, network access, and so on.

Let’s now open up this tutorial to explain the usage of Python try-except and try-except-else clauses.

Handle an arbitrary exception using try-except

Sometimes, you may need a way to allow any arbitrary exception and also want to be able to display the error or exception message.

It is easily achievable using the Python exceptions. Check the below code. While testing, you can place the code inside the try block in the below example.

try: #your code except Exception as ex: print(ex)

Catch multiple exceptions in a single except block

You can catch multiple exceptions in a single except block. See the below example.

except (Exception1, Exception2) as e: pass

Please note that you can separate the exceptions from the variable with a comma which is applicable in Python 2.6/2.7. But you can’t do it in Python 3. So, you should prefer to use the [as] keyword.

Handle multiple exceptions with one try-except block

There are many ways to handle multiple exceptions. The first of them requires placing all the exceptions that are likely to occur in the form of a tuple. Please see below.

try: file = open(‘input-file’, ‘open mode’) except (IOError, EOFError) as e: print(“Testing multiple exceptions. {}”.format(e.args[-1]))

The next method is to handle each exception in a dedicated except block. You can add as many except blocks as needed. See the below example.

try: file = open(‘input-file’, ‘open mode’) except EOFError as ex: print(“Caught the EOF error.”) raise ex except IOError as e: print(“Caught the I/O error.”) raise ex

Last but not least is to use the except without mentioning any exception attribute.

try: file = open(‘input-file’, ‘open mode’) except: # In case of any unhandled error, throw it away raise

This method can be useful if you don’t have any clue about the exception possibly thrown by your program.

How to re-raise exceptions in Python

Exceptions once raised keep moving up in the call stack. However, you can add an except clause which could just have a “raise” call without any argument. It’ll result in re-raising the exception.

See the below example code. In this code, we added a call to raise from the try-except block.

try: # Intentionally raise an exception. raise Exception(‘I learn Python!’) except: print(“Entered in except.”) # Re-raise the exception. raise

Output:

Entered in except. Traceback (most recent call last): File “python”, line 3, in

Exception: I learn Python!

When to use the else clause with try-except

Use an else clause right after the try-except block. The else clause will get hit only if no exception is thrown. The else statement should always precede the except blocks.

In else blocks, you can add code that you wish to run when no errors occur.

See the below example. In this sample, you can see a while loop running infinitely. The code asks for user input and then parses it using the built-in [int()] function. If the user enters a zero value, then the except block will get hit. Otherwise, the code will flow through the “else” block.

while True: # Enter integer value from the console. x = int(input()) # Divide 1 by x to test error cases try: result = 1 / x except: print(“Error case”) exit(0) else: print(“Pass case”) exit(1)

When should we use finally clause

It is simple if you have a code that you want to run in all situations, then write it inside the [finally block]. Python will always run the instructions coded in the [finally block]. It is the most common way of doing clean-up tasks. You can also make sure the clean-up gets through.

An error is caught by the try-except clause. After the code in the except block gets executed, the instructions in the [finally clause] will run.

Please note that a [finally block] will ALWAYS run, even if you’ve returned ahead of it.

See the below example.

try: # Intentionally raise an error. x = 1 / 0 except: # Except clause: print(“Error occurred”) finally: # Finally clause: print(“The [finally clause] is hit”)

Output:

Error occurred The [finally clause] is hit

Use the as keyword to catch specific exception types

With the help of the “as” keyword, we can create a new exception object inline.

Here, in the below example, we are creating the IOError object and then using it in the exception block.

try: # Intentionally raise an error. f = open(“no-file”) except IOError as err: # Creating IOError instance for book keeping. print(“Error:”, err) print(“Code:”, err.errno)

Output:

(‘Error:’, IOError(2, ‘No such file or directory’)) (‘Code:’, 2)

Best practice for manually raising exceptions

Avoid raising generic exceptions because if you do so, then all other more specific exceptions have to be caught also. Hence, the best practice is to raise the most specific exception close to your problem.

Bad example.

def bad_exception(): try: raise ValueError(‘Intentional – do not want this to get caught’) raise Exception(‘Exception to be handled’) except Exception as error: print(‘Inside the except block: ‘ + repr(error)) bad_exception()

Output:

Inside the except block: ValueError(‘Intentional – do not want this to get caught’,)

Best Practice:

Here, we are raising a specific type of exception, not a generic one. In this code, we are also using the args option to print the incorrect arguments if there are any. Let’s see the below example.

try: raise ValueError(‘Testing exceptions: The input is in incorrect order’, ‘one’, ‘two’, ‘four’) except ValueError as err: print(err.args)

Output:

(‘Testing exceptions: The input is in incorrect order’, ‘one’, ‘two’, ‘four’)

How to skip through errors and continue execution

Ideally, you shouldn’t be doing this. But if you still want to do it, then follow the below code to check how to skip an error using try-except.

try: assert False except AssertionError: pass print(‘Welcome to Prometheus!!!’)

Output:

Welcome to Prometheus!!!

Now, have a look at some of the most common Python exceptions and their examples.

Most common exception errors

Here is a list of the most common exceptions that can occur in Python code.

  • IOError – It occurs on errors like a file failing to open.
  • ImportError – If a Python module can’t be loaded or located.
  • ValueError – It occurs if a function gets an argument of the right type but an inappropriate value.
  • KeyboardInterrupt – It gets hit when the user enters the interrupt key (i.e. Control-C or Del key)
  • EOFError – It gets raised if the input functions (input()/raw_input()) hit an end-of-file condition (EOF) but without reading any data.
Examples of most common exceptions

The below Python code presents you with an excellent example of handling exceptions. By using the try-except mechanism, it is capturing five types of errors as well as an unknown exception.

ex_list = [IOError, ValueError, ImportError, EOFError, KeyboardInterrupt, any] for ex in ex_list: try: raise ex except IOError: print(‘1. Error occurred while opening the file.’) pass except ValueError: print(‘2. Non-numeric input detected.’) pass except ImportError: print(‘3. Unable to locate the module.’) pass except EOFError: print(‘4. Identified EOF error.’) pass except KeyboardInterrupt: print(‘5. Wrong keyboard input.’) pass except: print(‘6. An unknown error occurred.’) pass

Try Except in Python

Try and Except statement is used to handle these errors within our code in Python. The try block is used to check some code for errors i.e the code inside the try block will execute when there is no error in the program. Whereas the code inside the except block will execute whenever the program encounters some error in the preceding try block.

Syntax:

try:
# Some Code
except:
# Executed if error in the
# try block

How try() works?

  • First, the try clause is executed i.e. the code between try.
  • If there is no exception, then only the try clause will run, except clause is finished.
  • If any exception occurs, the try clause will be skipped and except clause will run.
  • If any exception occurs, but the except clause within the code doesn’t handle it, it is passed on to the outer try statements. If the exception is left unhandled, then the execution stops.
  • A try statement can have more than one except clause

Code 1: No exception, so the try clause will run.

Selenium Python Exception Handling | Selenium Python Tutorial
Selenium Python Exception Handling | Selenium Python Tutorial

Python3


def


divide(x, y):


try


result


print


"Yeah ! Your answer is :"


, result)


except


Exception as e:


print


"The error is: "


,e)


divide(


"GFG"


divide(

Output:

The error is: unsupported operand type(s) for //: ‘int’ and ‘str’
The error is: integer division or modulo by zero

Else Clause

In Python, you can also use the else clause on the try-except block which must be present after all the except clauses. The code enters the else block only if the try clause does not raise an exception.

Syntax:

try:
# Some Code
except:
# Executed if error in the
# try block
else:
# execute if no exception

Code:

Checking for javascript exceptions with selenium?

I’m utilizing Python’s Selenium library along with the Chrome backend for web automation using a web driver.

At the conclusion of each test, I want to verify that no javascript exceptions were thrown throughout the test. Essentially, I want to emulate the process of opening the JS console and searching for any red text. Is there a simple method to accomplish this using selenium? My intention is not to catch any specific javascript calls, but rather to identify any exceptions that might occur in the background, which may not necessarily result in a test failure.

Solution:

Brian Kitchener shared a blog post discussing a method for injecting JavaScript into every page to generate error messages. Although I haven’t personally tested it, it seems like he may be using Selenium RC. However, I believe it could easily be adapted to webdriver and serve as a useful starting point for your project.

Try.. & Except Has Some Secret Functionality in Python
Try.. & Except Has Some Secret Functionality in Python

Handling Errors and Exceptions in Selenium Python

Handling errors and exceptions in Selenium Python are vital when writing production-ready code, since exceptions and errors can arise for different reasons, as discussed earlier.

A prerequisite to writing tests using Selenium Python is to install Python and Selenium on your machine. When using Python for Selenium testing, the default framework used is PyUnit, also known as unittest, which is influenced by JUnit. It functions similarly to other unit testing frameworks.

However, in this blog on handling errors and exceptions in Selenium Python, we will use Pytest, another Python testing framework that supports functions, APIs, and unit testing. It is compatible with the current versions of Python and is easy to configure using the Python Package Manager (pip) command in the terminal.

If you are new to testing using Selenium Python, here is a detailed step-by-step tutorial on how to get started with Selenium Python. You will learn how to configure Python, Selenium, and Pytest on your machine to start automation testing with Selenium. You can learn more about Pytest through this Selenium Pytest tutorial.

For a different approach to handling exceptions, you might also explore exception handling in cypress, which can be useful in specific scenarios.

Project Setup

For the test project setup, we are using the Visual Studio (VS) Code IDE to write the test scripts. Alternatively, there are other IDEs available, such as Pycharm, Atom, and Sublime Text, that you can use as well.

For the package manager, we will use Poetry, a Python tool that manages and packages the necessary dependencies in a specific virtual environment for your project. You can declare the libraries your project depends on, and it will take care of managing (installing and updating) them.

  1. To install Poetry on your local machine’s terminal, please use the following command:
  • For Windows
  • For Mac


pip install poetry


pip3 install poetry

(depends on the Python version you are using).

  • selenium (v 4.3.0)
  • flake8 (v 4.0.1)
  • pytest (v 7.1.2)
  • pytest-xdist (v 2.5.0)
  • autopep8 (v 1.6.0)

The pytest-xdist plugin adds new test execution modes to Pytest, allowing us to run parallel Selenium Python tests. Autopep8 formats the Python code to adhere to the PEP 8 style manual. Flake8 is a great tool that tests your code for errors against the PEP 8 style guide.

10

11

12

13

14

15

16

17

18

19

[tool.poetry]

name = “tests”

version = “0.1.0”

description = “”

authors = [“Eugene Kwaka

“]

[tool.poetry.dependencies]

python = “^3.7”

selenium = “^4.3.0”

pytest = “^7.1.2”

pytest-xdist = “^2.5.0”

autopep8 = “^1.6.0”

flake8 = “^4.0.1”

[tool.poetry.dev-dependencies]

[build-system]

requires = [“poetry-core>=1.0.0”]

build-backend = “poetry.core.masonry.api”

To install the dependencies mentioned, run the following command to create the pyproject.toml and poetry.lock files in the directory.

A virtual environment (venv) containing the dependencies installed will be automatically created by Poetry. This is important since we do not want to mix Python’s global dependencies with the specific dependencies we require to run the tests in the project.

In our project, we create a folder that will hold the test functions. Let’s call it “seltests”.

Automate your Python tests in seconds. Try LambdaTest Now!

How do I catch all of these exceptions in python?

I am currently developing a
python program
program that allows users to input commands and performs their execution using

exec()

. Here is the progress I have made with the code:
“””.


>>> while True: ... var = raw_input('Enter the code: ') ... exec(var) ...

This section functions correctly. Nonetheless, my intention is to detect any error-raising user input and display the corresponding error message. Here is my approach:


>>> while True: ... try: ... var = raw_input('Enter the code: ') ... exec(var) ... except * as e: ... print e ...

This raises its own error:


File "


“, line 4 except * as e: ^ SyntaxError: invalid syntax

Why is this? Is it not the designated correct syntax for making exceptions?

Solution 1:

The syntax

is exclusively employed in imports. To utilize

Exception as e

and subsequently invoke

as the error message.

Solution 2:

The syntax you used is incorrect; here is the revised code.


>>> while True: ... try: ... var = raw_input('Enter the code: ') ... exec(var) ... except Exception as e: ... print e ...

Instead of utilizing

except * as e

, it is recommended to employ

except Exception as e

due to the fact that

lacks any associated value except in imports. However, it is advisable to minimize the presence of

try: ... except: ...

and exclude

raw_input()

from the try block, unless it is specifically desired to surround it as well.

Solution 3:

The correct syntax would be:


try: # some code except Exception as e: print e

Solution 4:

Your code contains a syntax error, rather than an exception. To catch all exceptions, the appropriate syntax is “””.


try:


except Exception as e: print e

The root of the exception hierarchy is “Exception,” which is responsible for capturing all program errors (excluding system errors). Refer to Section 8: Errors and Exceptions in the Python tutorial for more information.

Hướng dẫn dùng lệnh Try xử lý ngoại lệ trong Python
Hướng dẫn dùng lệnh Try xử lý ngoại lệ trong Python

Python3


def


divide(x, y):


try


result


print


"Yeah ! Your answer is :"


, result)


except


ZeroDivisionError:


print


"Sorry ! You are dividing by zero "


divide(

Output :

Sorry ! You are dividing by zero

Code 2: The other way of writing except statement, is shown below and in this way, it only accepts exceptions that you’re meant to catch or you can check which error is occurring.

Conclusion

In this blog, we have looked at some common exceptions in Selenium Python. We have also deep-dived into various exceptions and looked at why NoSuchElementException and StaleElementReference are generated and how to handle them. Selenium Python provides methods using which you can handle various exceptions, and in this case, we have focused on the try and except method.

Python or JavaScript - Which One Should YOU Learn?
Python or JavaScript – Which One Should YOU Learn?

I’m trying to automate processes on a webpage that loads frame by frame. I’m trying to set up a

try-except

loop which executes only after an element is confirmed present. This is the code I’ve set up:


from selenium.common.exceptions import NoSuchElementException while True: try: link = driver.find_element_by_xpath(linkAddress) except NoSuchElementException: time.sleep(2)

The above code does not work, while the following naive approach does:


time.sleep(2) link = driver.find_element_by_xpath(linkAddress)

Is there anything missing in the above try-except loop? I’ve tried various combinations, including using time.sleep() before

try

rather than after

except

.

Thanks

How To Handle Errors And Exceptions In Selenium Python

Eugene Kwaka

Posted On: July 20, 2022

584448 Views

18 Min Read

In the world of automation testing, Selenium is a free and open-source framework used to perform web application testing in web browsers like Chrome, Safari, Firefox, Opera, and Edge. You can write Selenium IDE tests using various programming languages such as Python, Java, JavaScript(Node.js), Kotlin, Ruby, PHP, and C#.

While the advantages of automated testing using Selenium are endless, there are incidences of errors and exceptions that happen regularly in the testing tool (or framework). When a program’s execution is disrupted during run-time, an exception is raised, preventing further instructions from being executed. Runtime errors are raised when you perform an unanticipated operation during runtime.

Exception and error handling is a programming mechanism by which the occurrence of errors and exceptions that halt the execution of a program are responded to by the program to ensure the normal execution of code.

In this blog on handling exceptions in Selenium Python, we will look at the variety of exceptions and errors that can happen when a Selenium test is running. By the end of this blog, you will be able to implement error and exception handling for Selenium automation tests.

So, let’s get started!

TABLE OF CONTENTS

What are the Exception types in Selenium?

Checked Exceptions are handled during the process of writing the codes. At that time, these exceptions are handled before the compiling process. If it happens, such an exception is examined at the compile time. Checked Exceptions are the ones that are handled at the time when the code is compiled. These exceptions have to be handled at compile time, and hence, these exceptions get examined before compiling the code.

Got Questions? Drop them on LambdaTest Community. Visit now

Selenium Full Course [2024] | Learn Selenium | Selenium Tutorial For Beginners | Edureka
Selenium Full Course [2024] | Learn Selenium | Selenium Tutorial For Beginners | Edureka

Exceptions in Selenium Python

Exceptions are of primary use when you are writing development-ready code especially which is at a high risk of causing a certain type of exception. So here is a list of all exceptions in Selenium Python.

Exception Description
ElementClickInterceptedException The Element Click command could not be completed because the element receiving the events is obscuring the element that was requested clicked.
ElementNotInteractableException Thrown when an element is present in the DOM but interactions with that element will hit another element do to paint order
ElementNotSelectableException Thrown when trying to select an unselectable element.
ElementNotVisibleException Thrown when an element is present on the DOM, but it is not visible, and so is not able to be interacted with.
ErrorInResponseException Thrown when an error has occurred on the server side.
ImeActivationFailedException Thrown when activating an IME engine has failed.
ImeNotAvailableException Thrown when IME support is not available.
InsecureCertificateException Navigation caused the user agent to hit a certificate warning, which is usually the result of an expired or invalid TLS certificate.
InvalidArgumentException The arguments passed to a command are either invalid or malformed.
InvalidCookieDomainException Thrown when attempting to add a cookie under a different domain than the current URL.
InvalidCoordinatesException The coordinates provided to an interactions operation are invalid.
InvalidElementStateException Thrown when a command could not be completed because the element is in an invalid state.
InvalidSelectorException Thrown when the selector which is used to find an element does not return a WebElement.
InvalidSessionIdException Occurs if the given session id is not in the list of active sessions, meaning the session either does not exist or that it’s not active.
InvalidSwitchToTargetException Thrown when frame or window target to be switched doesn’t exist.
MoveTargetOutOfBoundsException Thrown when the target provided to the ActionsChains move() method is invalid, i.e. out of document.
NoAlertPresentException Thrown when switching to no presented alert.
NoSuchAttributeException Thrown when the attribute of element could not be found.
NoSuchCookieException No cookie matching the given path name was found amongst the associated cookies of the current browsing context’s active document.
NoSuchFrameException Thrown when frame target to be switched doesn’t exist.
NoSuchWindowException Thrown when window target to be switched doesn’t exist.
StaleElementReferenceException Thrown when a reference to an element is now “stale”.
TimeoutException Thrown when a command does not complete in enough time.
UnableToSetCookieException Thrown when a driver fails to set a cookie.
UnexpectedAlertPresentException Thrown when an unexpected alert is appeared.
UnexpectedTagNameException Thrown when a support class did not get an expected web element

Don’t miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.

Dive into the future of technology – explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.

Last Updated :
04 Apr, 2023

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment…

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions.I am sure we have encountered exceptions in multiple scenarios during our Selenium automation process.

As part of testing many a times we want the test to fail when there is an error.This is true for most of the times.There are some situations where we want to handle errors differently than simply letting it fail.

Without proper error handling the program could come to a complete halt and stop execution of the further important steps.Exception handling become vital in this case so as to save time and ensure the program is executed successfully.

The exception classes are available in selenium.common.exceptions.Selenium exceptions can be classified as checked exceptions and unchecked exceptions.

Checked exceptions are exceptions that are handled during the writing of the code.These are typically handled before compiling the code.

Unchecked exceptions are thrown at runtime.These exceptions are ignored by the complier.

Common Exceptions in Selenium Python

According to a recent Stack Overflow developer survey, Python is the fourth most popular programming language among developers.

It offers a robust support system for test automation frameworks and is the most user-friendly and straightforward programming language available.

Errors and exceptions in Selenium Python are common and can occur when writing tests. The exception instances must be derived from a class that inherits from BaseException. If two exception instances do not have a subclass relationship, they are not considered equal despite having the same properties, such as names.

While writing code for the test scripts, the code can run into built-in exceptions, or you can raise exceptions in the code. The interpreter or built-in functions generate the built-in exceptions.

The selenium.common.exceptions package contains the exception classes, which can be imported in the following way.

Syntax: from selenium.common.exceptions import [Exception Name]

An example of an exception being imported is below:

This exception indicates that the website does not contain the attribute of the element being looked for.

Other exceptions in Selenium Python include:TimeOutException.NoSuchElementException.ElementNotInteractableException.ElementNotVisibleException.StaleElementReferenceException.ElementClickInterceptedException.NoSuchCookieException.InvalidArgumentException.InvalidElementStateException.NoSuchWindowException.

  • TimeOutException

When a command does not complete in the time duration set (seconds), this exception is raised or thrown. The wait time can either be implicitly or explicitly defined.

  • NoSuchElementException

When an element cannot be found, this exception is raised or thrown. Nonetheless, different factors can lead to this exception being generated:

  • The element is not yet in the DOM when the find operation is performed because the page loading is in progress.
  • Incorrect element locator is used in the source code.
  • ElementNotInteractableException

Such exceptions in Selenium Python is raised whenever an element in the DOM is present but cannot be interacted with.

  • ElementNotVisibleException

This exception typically arises when the interaction involves clicking or reading text from an element that is not visible in the DOM.

  • StaleElementReferenceException

An outdated or unavailable element in the DOM is referred to as a stale element. A reference to an element that is currently “stale” will raise or throw this exception.

For example, the following reasons could lead to the StaleElementReferenceException exception:

  • After the element was located, the page either changed or was refreshed.
  • A refreshed context may have contained the element.
  • Complete deletion of the referenced web element.
  • ElementClickInterceptedException

This exception arises when the element receiving the interaction impedes the element intended to be clicked, thereby preventing the Element Click operation from being performed.

  • NoSuchCookieException

This exception will be raised if a cookie with the specified path name is not contained amongst the corresponding cookies of an active document in the current browsing session. To learn more about cookies in Selenium, check out this detailed tutorial on handling cookies in the Selenium WebDriver.

  • InvalidArgumentException

Watch this video to understand how you can handle Cookies and perform different operations like deleting, getting the parameter values, and adding them to Selenium WebDriver using Java.

A command with improper or incorrect argument inputs will raise an InvalidArgumentException.

  • InvalidElementStateException

This exception is raised when we try to perform an operation that does not apply to an element. For example, if we perform a click operation on a radio button that is disabled, the exception will be raised, and hence the command given cannot be executed.

  • NoSuchWindowException

This exception is thrown when the intended window target cannot be found.

If you are a Python programmer looking to make a mark, you can take your career to the next level with the Selenium Python 101 certification from LambdaTest.

Here’s a short glimpse of the Selenium Python 101 certification from LambdaTest:

Trích xuất dữ liệu từ bất kỳ trang Web nào sử dụng Selenium trong Python | Crawl Data Using Selenium
Trích xuất dữ liệu từ bất kỳ trang Web nào sử dụng Selenium trong Python | Crawl Data Using Selenium

Python3


from


selenium


import


webdriver


from


selenium.webdriver.common.by


import


By


driver


webdriver.Firefox()


driver.get("https:


www.geeksforgeeks.org


")


element


driver.find_element(By.LINK_TEXT, "abrakadabra")


print


(element.click())

Now, let’s run this program, it first open geeksforgeeks.org and then raise exception – selenium.common.exceptions.NoSuchElementException, which means that element doesn’t exist on the website.

Keywords searched by users: try except selenium python

Selenium Python Exception Handling | Selenium Python Tutorial - Youtube
Selenium Python Exception Handling | Selenium Python Tutorial – Youtube
Python Try Except: An Illustrated Guide – Be On The Right Side Of Change
Python Try Except: An Illustrated Guide – Be On The Right Side Of Change
Selenium Python Exception Handling | Selenium Python Tutorial - Youtube
Selenium Python Exception Handling | Selenium Python Tutorial – Youtube
Selenium Python Exception Handling | Selenium Python Tutorial - Youtube
Selenium Python Exception Handling | Selenium Python Tutorial – Youtube
Selenium Wait For Page To Load - Python Tutorial
Selenium Wait For Page To Load – Python Tutorial
Nested Try In Java | Nested Try Catch Java - Scientech Easy
Nested Try In Java | Nested Try Catch Java – Scientech Easy
How To Print Exception Messages In Python (Try-Except) – Be On The Right  Side Of Change
How To Print Exception Messages In Python (Try-Except) – Be On The Right Side Of Change
Try Catch In Java: Exception Handling Example
Try Catch In Java: Exception Handling Example
Selenium Python Exception Handling | Selenium Python Tutorial - Youtube
Selenium Python Exception Handling | Selenium Python Tutorial – Youtube
Exception Groups In Python - Geeksforgeeks
Exception Groups In Python – Geeksforgeeks

See more here: kientrucannam.vn

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *