Home > Software engineering >  How to change between iframes in Selenium and Python
How to change between iframes in Selenium and Python

Time:02-08

I was trying to understand how to change between iframes in selenium webdriver, but I could not figure it out. In the image ahead, is the iframe that I want to switch to:

Snapshot:

iframe

CodePudding user response:

 //iframe[@class='viewer pbi-frame']

Should be a simple xpath using driver.switch_to.frame()

Or

 //iframe[@title='Power BI Report Viewer']

CodePudding user response:

In order to switch to the iframe you can use code like this:

driver.switch_to.frame(driver.find_element_by_css_selector("//iframe[@title='PowerBi Report Viewer']"))

When finished working inside the iframe you will have to switch back to the default content with

driver.switch_to.default_content()

CodePudding user response:

The website is Power BI based, so to switch within the <iframe> 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, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[title='PowerBi Report Viewer']")))
      
    • Using XPATH:

      WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@title='PowerBi Report Viewer']")))
      
  • 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:

  •  Tags:  
  • Related