'Want to switch to a iframe in Selenium Python

I want to switch to an iframe in a tab. This iframe is a video player on the website that i do online classes for. I am trying to switch to the iframe with this piece of code

try: 
    iframe = driver.find_element(By.ID, 'iFramePreview')
    WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.ID ,'iFramePreview'))) 
    driver.switch_to_frame(iframe) 
except:
    print("can't find video")
else:
    iframe = driver.find_element(By.XPATH, '//*[@id="stageFrame"]')
    WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, '//*[@id="stageFrame"]'))) 
    driver.switch_to_frame(iframe) 

There are two iframes that i can identify in the source code that is usefull for me to switch to. Please let me know if i am on the right track or i should use a different method.

The first iframe HTML code on the website is:

<iframe allow="autoplay; fullscreen" id="iFramePreview" 
onload="iFrameNotify.notify({frame: window.parent,message:'ChildFrameLoaded'});" 
hspace="0" vspace="0" frameborder="0" 
src="//media.edgenuity.com/contentengine/frames/6d7891d2-3173-11e7-932f-bc764e05edf3/6d7891d2-3173-11e7-932f-bc764e05edf3.html" style="width: 854px; height: 480px; display: none;"></iframe>

The second is:

<iframe allow="autoplay; fullscreen; microphone *" id="stageFrame" 
onload="iFrameNotify.notify({frame: window,message:'ChildFrameLoaded'});" 
name="stageFrame" frameborder="0" seamless="" scrolling="auto" data-bind="attr: 
{ src: $root.stageView().Url }" src="https://r17.core.learn.edgenuity.com/Player/LTILaunch"></iframe>

The errors I got without using the try and except is:

  File "c:\Users\shakt\hello2\edgenuityBot.py", line 176, in <module>
    iframe = driver.find_element(By.ID, 'iFramePreview')

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="iFramePreview"]"}



Sources

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

Source: Stack Overflow

Solution Source