Yulia Kentieva
Yulia Kentieva

Reputation: 720

How to use try/catch with selenium python to check the absence of an element?

I need to refresh the page if the element is not there and proceed to downstream code whenever it appears. My code:

Button=False

while not Button:

try:
    Btn = addButton = browser.find_element_by_class_name("my button")
    print("Button isn't there")
    time.sleep(1)
    browser.refresh()

except:

    Btn = addButton = browser.find_element_by_class_name("my button")
    print("Button was clicked")
    Btn.click()
    Button = True

I need to fix the "try" part to check if the "my button" is NOT there, so it keeps refreshing the page

Upvotes: 0

Views: 1532

Answers (2)

Arundeep Chohan
Arundeep Chohan

Reputation: 9969

While True:
    try:
        time.sleep(1)
        Btn = browser.find_element_by_class_name("my button")
        Btn.click()
        break
    except:
        print("Button isn't there")
        browser.refresh()

Look for the btn to be there and click it if it isn't just refresh the page. However this can be done using Webdriver waits which will be much better. Look above at Z4-tier's answer which is the proper way to use Selenium.

Upvotes: 0

Z4-tier
Z4-tier

Reputation: 7988

If we translate this code into regular language, it might look something like this:

Assume that the button is not there. It is an error for the button to be there. If an error occurs, assume it is because the button was present, and click the button. If no error occurs, refresh the page forever until the button appears.

The thing is, it's not an error if the button is on the page, it's an expected behavior. So don't use a try-except block to handle that behavior.

Next, polling on page elements with Selenium is not idiomatic and a big anti-pattern. Don't do it. Use timeouts and wait objects to handle it instead.

Here is an example:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.common.exceptions import ElementNotVisibleException, ElementNotSelectableException

driver = webdriver.Firefox() # or chrome...
fluent_wait = WebDriverWait(driver, 10, poll_frequency=1, ignored_exceptions=[ElementNotVisibleException, ElementNotSelectableException])
elem = wait.until(EC.element_to_be_clickable((By.XPATH, "x_path_to_the_button")))
if not elem:
    print("Button isn't there")
    driver.refresh()
else:
    print("Button was clicked")
    elem.click()

Upvotes: 1

Related Questions