How to change between iframes in Selenium and Python

117
April 08, 2022, at 10:50 AM

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:

Answer 1

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:

  • Switch to an iframe through Selenium and python
  • selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element while trying to click Next button with selenium
  • selenium in python : NoSuchElementException: Message: no such element: Unable to locate element
Answer 2
 //iframe[@class='viewer pbi-frame']

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

Or

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

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()
Rent Charter Buses Company
READ ALSO
Removing multiple headers in a single excel sheet

Removing multiple headers in a single excel sheet

Similar to Remove header row in Excel using pandas

86
How to bulk rename JSON files?

How to bulk rename JSON files?

I am trying to rename and replace a certain text with the hexadecimal for thousands of JSON files

70
How to add legend to plotly graph_objects plot that describes the colors, not traces?

How to add legend to plotly graph_objects plot that describes the colors, not traces?

I would like to have a legend on the right side of my plot that has 10 different color points & (representing the 10 different clusters in the graph below)I've provided two lists before, one that contains the color of each point, and the other list contains...

101