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)