Selenium Find Element Return None if Not Found (avoid NoSuchElementException) - Python

June 13, 2019

find_element_by_css_selector will raise NoSuchElementException if element not found.

from selenium.common.exceptions import NoSuchElementException

def find_element_by_css_selector(driver, css_selector):
    try:
        return driver.find_element_by_css_selector(css_selector)
    except NoSuchElementException as e:
        return None

el = find_element_by_css_selector(item_el, 'h1')
if el:
    print(el.text)

find_elements_by_css_selector return empty list if elements not found.

el = driver.find_element_by_css_selector('h1')
if el:
    print(el[0].text)
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.