'IF CONDITION doesn't work between Recaptcha and another Element, just 1 works. Selenium python

I am trying to do if-else condition for Selenium Python with Recaptcha.

I'm checking a website and sometimes a Recaptcha appears to solve.

and sometimes it doesn't appear and the submit button can be clicked.

I want the code to switch to Recaptcha and solve if it appears and click the submit button if not.

my tries

search_box = driver.find_element(By.ID,"SearchCriteria")
search_box.send_keys("Test")

WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[name^='a-'][src^='https://www.google.com/recaptcha/api2/anchor?']")))
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//span[@id='recaptcha-anchor']"))).click()
driver.switch_to.default_content()

try:
    driver.find_element(By.ID,"btnSSSubmit").click()

except:
    WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[title='recaptcha challenge expires in two minutes']")))
    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button#recaptcha-"))).click()

This method doesn't seem to work when Recaptcha doesn't pop up I'm guessing because the next portion of code is attempting to solve the Recaptcha and since it doesn't pop up it causes an error.

The 2nd method I tried

search_box = driver.find_element(By.ID,"SearchCriteria")
search_box.send_keys("Test")

WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[name^='a-'][src^='https://www.google.com/recaptcha/api2/anchor?']")))
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//span[@id='recaptcha-anchor']"))).click()
driver.switch_to.default_content() 
try:
    if(len(driver.find_elements(By.XPATH, "btnSSSubmit"))) > 0 :
        WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID,"btnSSSubmit"))).click()

        WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[title='recaptcha challenge expires in two minutes']")))
        WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button#recaptcha"))).click()
except:
    pass

This method doesn't work if the Recaptcha doesn't appear.

Any help please would be appreciated.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source