Close Menu
TechBeamersTechBeamers
    TechBeamersTechBeamers
    • Python
    • Java
    • C
    • SQL
    • MySQL
    • Selenium
    • Testing
    • Agile
    • Linux
    • WebDev
    • Technology
    TechBeamersTechBeamers
    Python Selenium

    How to Switch Between IFrames Using Selenium Python

    By Meenakshi AgarwalUpdated:Oct 31, 2023No Comments4 Mins Read
    Share
    Facebook Twitter LinkedIn Pinterest Email

    In this Selenium Python tutorial, we’ll learn to switch between IFrames. An IFrame (Inline Frame) is an HTML element that allows rendering a document within another HTML document on a webpage.

    We prefer to use IFrames when we aspire to host content from an external source on our webpage. It could be an image, a video, advertisements from other vendors, to highlight some information, etc.

    HTML provides “< iframe > < /iframe >” tags to identify an IFrame inside an HTML document.

    Switch Between IFrames Using Selenium Python

    Switch Between IFrames Selenium Python
    Switch Between IFrames: Selenium Python

    If a webpage contains multiple IFrames, then we will need to switch between them. Selenium Python API provides “switch_to.iframe (self, frame_reference)” method to move to a particular IFrame.

    driver.switch_to.iframe(self,frame reference)

    Where,

    the “<frame_reference>” parameter is the locator used to identify the IFrame.

    Let’s take a sample HTML code that will create multiple IFrames in the web page.

    <!DOCTYPE html>
    <html>
    <head>
    <title>Switching Between IFrames Demo</title>
    </head>
    <body>
    <h1>Welcome Viewers</h1>
    <iframe name="frame1" id="FR1" src="//www.techbeamers.com" height="500" width="400"> </iframe>
    <iframe name="frame2" id="FR2" height="500" width="400" src="http://www.seleniumhq.org"> </iframe>
    </body>
    </html>

    There are two IFrames embedded in this web page. To perform switching between the above IFrames first, we have to locate them on the web page. Take a look at the code; it provides three different mechanisms by which we can do this. They are.

    • By using the tag name ( in this case ‘iframe’)
    • By using the Id of IFrame
    • By using the name of IFrame

    Here is the specified code snippet to perform switching between frames.

    from selenium import webdriver
    
    from selenium.webdriver.common.keys import Keys
    
    from selenium.webdriver.common.by import By
    
    import time
    
    driver = webdriver.Firefox()
    
    driver.maximize_window()
    
    location = "file://<Specify Path to IFrame.HTML>"
    
    driver.get(location)
    
    ########Section-1
    
    # get the list of iframes present on the web page using tag "iframe"
    
    seq = driver.find_elements_by_tag_name('iframe')
    
    print("No of frames present in the web page are: ", len(seq))
    
    #switching between the iframes based on index
    
    for index in range(len(seq)):
    
        driver.switch_to_default_content()
    
        iframe = driver.find_elements_by_tag_name('iframe')[index]
    
        driver.switch_to.frame(iframe)
    
        driver.implicitly_wait(30)
    
        #highlight the contents of the selected iframe
    
        driver.find_element_by_tag_name('a').send_keys(Keys.CONTROL, 'a')
    
        time.sleep(2)
    
        # undo the selection within the iframe
    
        driver.find_element_by_tag_name('p').click()
    
        driver.implicitly_wait(30)
    
    driver.switch_to.default_content()
    
    ########Section-2
    
    #switch to a specific iframe (First frame) using Id as locator
    
    iframe = driver.find_element_by_id('FR1')
    
    driver.switch_to.frame(iframe)
    
    time.sleep(2)
    
    driver.find_element_by_id('s').send_keys("Selected")
    
    driver.switch_to.default_content()
    
    ########Section-3
    
    #switch to a specific iframe (Second frame) using name as locator
    
    iframe = driver.find_element_by_name('frame2')
    
    driver.switch_to.frame(iframe)
    
    time.sleep(2)
    
    driver.find_element_by_tag_name('a').send_keys(Keys.CONTROL, 'a')

    Let’s analyze the above code step by step.

    See also  Higher Order Functions in Python

    1) First of all, you must save the HTML code, given above as IFrame.HTML on your machine.

    2) Next, you must provide the correct path in the placeholder given in the above snippet. You must use forward slash while specifying the file-path of the web page. Otherwise, it may not work accurately. For example, here I have given the path of the file as.

    location = "file://C:/Users/Automation-Dev/Desktop/selenium/IFrame.HTML"

    3) In Section-1 of the code,

    seq= driver.find_elements_by_tag_name('iframe')

    provides the list of IFrames present on the web page.

    4) We do the switching between the IFrames by traversing through this list using the following step.

     iframe = driver.find_elements_by_tag_name('iframe')[index]
    
     driver.switch_to.frame(iframe)

    5) Every time you need to move back from an IFrame to the parent HTML. Selenium Webdriver provides the following method.

    driver.switch_to.default_content()

    6) In Section-2, we switch to a specific IFrame using the locator as ‘id.’

     iframe = driver.find_element_by_id('FR1')

    7) In Section-3, we switch to a specific IFrame using the locator as ‘name.’

    iframe = driver.find_element_by_name('frame2')

    Quick Wrapup

    It is essential to understand how to use Selenium Python to switch between IFrames. You can re-use this technique to solve real-time use cases in your projects.

    For more updates on Selenium Python tutorials, follow us on social media and share this post as well.

    Best,

    TechBeamers

    Previous ArticleHow to Switch Between Windows Using Selenium Python
    Next Article How to Handle Alert & Pop-up Boxes in Selenium Python
    Meenakshi Agarwal

    I'm Meenakshi Agarwal, founder of TechBeamers.com, with 10+ years of experience in Software development, testing, and automation. Proficient in Python, Java, Selenium, SQL, & C-Sharp, I create tutorials, quizzes, exercises and interview questions on diverse tech topics. Follow my tutorials for valuable insights!

    Add A Comment

    Leave A Reply Cancel Reply

    Python Coding Exercises for Beginners
    • 40 Python Exercises for Beginners
    • 6 Python Data Class Exercises
    • 100+ Python Interview Questions for 2024
    • 20 Python Programs to Print Patterns
    Python Basic Tutorials
    • Python Keyword
    • Python Statement
    • Python Comment
    • Python Data Types
    • Python String Methods
    • Python Multiline Strings
    • Python Split Strings
    • Python Slice Strings
    • Iterate Strings in Python
    • Python String Format
    • Python String Concatenation
    • Python Permutations of a String
    • Python Numbers
    • Python List
    • Python List Reverse
    • Python List Slice
    • Python Nested List
    • Python Set
    • Python Tuple
    • Python Dictionary
    • Python Dict to JSON
    • Python Dictionary Examples
    • Python OrderedDict
    • Python Arrays
    • Python Generate SubArrays
    • Python Heapq (Heap queue)
    • Python Operators
    • Python XOR Operator
    • Operator Precedence
    • Python Namespace
    • Python For Loop
    • Python While Loop
    • Python If Else
    • Python Switch Case
    • Python Function
    • Higher Order Functions in Python
    • Python Class
    • Python Class Definition
    • Python Data Class
    • Python Inheritance
    • Python Multiple Inheritance
    • Python Static Method
    • File Handling in Python
    • Python Copy File
    • Python Exception Handling
    • Python Try Except
    • Python Lambda
    • Python Generator
    • Python Module
    Python Pandas in Action
    • Rename Columns using Pandas
    • Python Pandas to Read CSV Files
    • Python Pandas to Merge CSV Files
    • Python Dictionary to DataFrame
    • Python Find Length of List
    Python Important Functions
    • Python Glob()
    • Python Range()
    • Python Float Range()
    • Python Map()
    • Python Filter()
    • Python Enumerate()
    • Python Zip()
    • Python Join()
    • Python Ord()
    Python Advanced Tutorials
    • Python Multithreading
    • Python Socket Programming
    • Selenium Python
    • Python Unittest
    • Python Time Module
    • Python Datetime
    • Python IRC
    • PyLint in Python
    • Python Random Number
    • Python MongoDB
    • Python Pickle
    Python Code Examples
    • Python List Contains Elements
    • Python Search Dictionary by Value
    • Python Check Type of Variable
    • Python Check Version Using Code
    • Python Loop Through Files
    • Compare Strings in Python
    • Replace Strings in Python
    • Size of Integer in Python
    • Simple Socket in Python
    • Threaded Socket in Python
    Python Tips & Tricks
    • 30 Essential Python Tips
    • 10 Python Coding Tips
    • 12 Python Code Optimization Tips
    • 10 Python Programming Mistakes
    Python General Topics
    • Top 10 Python IDEs
    • Top 7 Python Interpreters
    • Top 7 Websites for Python
    • Top 5 Chrome Plugin for Python
    Python Quizzes - General
    • Python Quiz-1
    • Python Quiz-2
    • Python Quiz-3
    • Python Quiz-4
    Python Quizzes - Advanced
    • Python Quiz - Data Structures
    • Python Quiz - Threads
    • Python Quiz - DA
    Python MCQ - Strings
    • Python MCQ Strings-1
    • Python MCQ Strings-2
    Python MCQ - Classes `
    • Python MCQ Classes-1
    • Python MCQ Classes-2
    Python MCQ - Functions
    • Python MCQ Functions-1
    • Python MCQ Functions-2
    Python MCQ - File I/O
    • Python MCQ File I/O-1
    • Python MCQ File I/O-2
    Latest Posts
    • 30 Python Programming Questions On List, Tuple, and Dictionary
    • 4 Different Ways to Rename Columns in Pandas
    • 4 Unique Ways to Reverse a String in Python
    • 40 Google Interview Questions You Need to Join Google in 2023
    • 40 Python Exercises for Beginners
    • 44 Python Data Analyst Interview Questions
    • 7 Websites to Learn Python Programming

    Subscribe to Updates

    Get the latest tutorials from TechBeamers.

    Loading
    • About
    • Contact
    • Disclaimer
    • Privacy Policy
    • Terms of Use
    © 2023 TechBeamers. All Rights Reserved.

    Type above and press Enter to search. Press Esc to cancel.