Python Selenium find_element_by_id with default if not found

Issue

I would like to find an element on the page by id. The issue is that this element is only temporary and will not exist all of the time. Therefore I would like to set the default value so I can check for it in a conditional like so:

    covidPopUp = driver.find_element_by_id("sgpb-popup-dialog-main- 
    div").extract(default='not-found')

    if(covidPopUp == 'not-found'):
        load_more_btn = driver.find_element_by_id("load_more_button")
        load_more_btn.click()
    else:
        popUpClose = driver.find_element_by_id("sgpb-popup-close-button-6")
        popUpClose.click()

However, this produces the following error:

AttributeError: 'WebElement' object has no attribute 'extract'

Solution

I think you have a couple of options.

  1. Use find_element_by_id but catch the exception
from selenium.common.exceptions import NoSuchElementException
try:
    covidPopUp = driver.find_element_by_id("sgpb-popup-dialog-main-div")
except NoSuchElementException:
    covidPopUp = "not-found"
  1. Use find_elements_by_id (note plural) and check if list is not empty.
covidPopUp = driver.find_elements_by_id("sgpb-popup-dialog-main-div")
covidPopUp = covidPopUp[0] if covidPopUp else "not-found"

Answered By – tomjn

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published