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

Time:03-02

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.

CodePudding user response:

Try like below once.

Since its the Recaptcha that may or may not appear, attempt to click on the Recaptcha in the Try block. And then click on the Submit button.

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

try:
    # Try to solve the Recaptcha.
except:
    print("Recaptcha did not appear")

WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID,"btnSSSubmit"))).click()
  • Related