1

I'm running a test case and part of it is to check if an element in an iframe is visible I have done the below but it's not working and always goes to the except block. Thank you

try:
    time.sleep(2)
    driver.switch_to.frame("iframe-xxxxxxxxxxxxxxxxxx")
    time.sleep(2)
    if driver.find_element_by_xpath("//div[@class='col-11 answer-feedback-label']//div[contains(text(),'Hello World!')]"):
        logging.info("Success")
except:
     logging.error("Failure")
Guy
  • 46,488
  • 10
  • 44
  • 88
Ryan
  • 129
  • 1
  • 12
  • 2
    Post the html. You should also remove the `try - except`, you are masking the error message that tells you what is the problem. – Guy Dec 24 '19 at 06:25
  • Use "except Exception as e: print(e)" to print error message. – Yun Dec 24 '19 at 06:32

1 Answers1

1

To check if an element in an <iframe> is visible or not, as the the desired element is with in an <iframe> so you have to:

  • Induce WebDriverWait for the desired frame_to_be_available_and_switch_to_it().
  • Induce WebDriverWait for the visibility_of_element_located().
  • You can use the following solution:

    • Code Block:

      from selenium import webdriver
      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.support import expected_conditions as EC
      from selenium.webdriver.common.by import By
      import org.openqa.selenium.TimeoutException;
      .
      .
      .
      try:
      
          WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"iframe_XPATH")))
          WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='col-11 answer-feedback-label']//div[contains(text(),'Hello World!')]")))
          logging.info("Success")
      except TimeoutEception:
           logging.error("Failure")
      

Here you can find a relevant discussion on Ways to deal with #document under iframe

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352