Search code examples
pythonseleniumiframewebdriverwaitexpected-condition

How to switch Selenium focus within an iframe using Python


I am unable to select a checkbox from a drop down menu on site. The dropdown is inside a iframe and when i try and switch to the iframe i keep getting TimeoutException message:.

Below is the code I'm trying and the HTML. I am new to Python so any help on this would be much appreciated.

Python:

wait = WebDriverWait(driver, 20)

frm1= wait.until(EC.presence_of_element_located((By.ID, "ReportViewerControl_ctl04_ctl03_ctl01")))

driver.switch_to.frame(frm1)

HTML:

<iframe id="ReportViewerControl_ctl04_ctl03_ctl01" onclick="event.cancelBubble=true;" onactivate="event.cancelBubble=true;" style="display: block; position: absolute; z-index: 10; left: 208px; top: 35px; width: 198px; height: 166px;" src="javascript:'';" frameborder="0" title="Area place holder" longdesc="Area place holder" name="ReportViewerControl_ctl04_ctl03_ctl01"></iframe>

Solution

  • To switch Selenium's focus within the <iframe> instead of presence_of_element_located() so you have to:

    • Induce WebDriverWait for the desired frame to be available and switch to it.
    • You can use either of the following Locator Strategies:
      • Using CSS_SELECTOR:

        WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[name^='ReportViewerControl'][longdesc='Area place holder']")))
        
      • Using XPATH:

        WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[starts-with(@id, 'ReportViewerControl') and @title='Area place holder']")))
        
      • Note : You have to add the following imports :

        from selenium.webdriver.support.ui import WebDriverWait
        from selenium.webdriver.common.by import By
        from selenium.webdriver.support import expected_conditions as EC
        

    Reference

    You can find a couple of relevant discussions in: