Selenium Python Exception Handling | SDET Unicorns

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 –

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! 

Leave a Reply

Your email address will not be published. Required fields are marked *