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

Jun 13, 2019

find_element_by_css_selector will raise NoSuchElementException if element not found.

from selenium.common.exceptions import NoSuchElementExceptiondef find_element_by_css_selector(driver, css_selector):    try:        return driver.find_element_by_css_selector(css_selector)    except NoSuchElementException as e:        return Noneel = 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)

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.