Search code examples
seleniumiframepytestframes

frames in selenium pytest


Hi I have parent frame called "bottomframe" inside that have two child frames called "Header" and "Main" I would like to switch between frames "Header" and "Main" but I am not able to come out from one sub frame.

<iframe id="bottomframe" name="bottomframe" scrolling="yes" src="Home_content.aspx?C=93&amp;L=YTERPIT%40WIN.DESY.DE&amp;sysMsg=0" width="100%" height="100%" align="left"></td></tr></table><input type="hidden" name="iprocure24url" value="https://iprocure.eu1.inforcloudsuite.com/xfel" /></body></html></iframe>
    <frameset rows="75,*" bgcolor="lightgrey" border="0"><frame src="punchoutheader.aspx?EvendorKey= 3257" name="Header" marginwidth="0" marginheight="0" width="100%" height="100%" scrolling="no"><frame src="OciPunchOutPage.aspx?EvendorKey= 3257" name="Main" marginwidth="0" marginheight="0" width="100%" height="100%"></frameset>
        <frame src="punchoutheader.aspx?EvendorKey= 3257" name="Header" marginwidth="0" marginheight="0" width="100%" height="100%" scrolling="no">
        </frame>
        <frame src="OciPunchOutPage.aspx?EvendorKey= 3257" name="Main" marginwidth="0" marginheight="0" width="100%" height="100%">
        </frame>
    </frameset>     
</iframe>

I tried below in pytest with selenium

driver.switch_to.frame("bottomframe")
driver.switch_to.frame("Header")
bodyText = driver.find_element_by_tag_name('body').text
print(bodyText)

This above works fine but now I would like to switch to another subframe "Main" so I tried below

driver.switch_to.frame("bottomframe")
driver.switch_to.frame("Header")
bodyText = driver.find_element_by_tag_name('body').text
print(bodyText)    
# back to default web page frame
driver.switch_to.default_content()
driver.switch_to.frame("bottomframe")
driver.switch_to.frame("Main") 

and i get NoSuchFrameException if I go to "Main" frame. Could you help me out to switch between frames "Main" and "Header"


Solution

  • A good approach

    A better way to switch frames will be to induce WebDriverWait for the availability of the intended frame with expected_conditions set to frame_to_be_available_and_switch_to_it as follows

    WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.NAME,"Main")))
    

    OR

    WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//frame[@name='Main']")))
    

    Switching back from frame

    To switch back to the Parent Frame you can use the following line of code:

    driver.switch_to.parent_frame()
    

    To switch back to the Top Level Browsing Context / Top Window you can use the following line of code:

    driver.switch_to.default_content()