TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: How to Switch Between Windows Using Selenium Python
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python SeleniumPython Tutorials

How to Switch Between Windows Using Selenium Python

Last updated: Oct 30, 2023 11:14 am
By Meenakshi Agarwal
Share
3 Min Read
Switch Between Windows Selenium Python
Switch Between Windows : Selenium Python
SHARE

In this Selenium Python tutorial, we’ll learn to switch between windows. While working on a website, it is highly possible that we open a large number of windows.

Contents
Selenium Python code to switch between windowsAbout the code to switch between windowsPoint-by-point summary

Each window may require us to perform some actions to complete an end-to-end flow. For this, we should be able to switch between them.

We need to switch over the control also and then do the required operation, because, by default, the focus remains on the parent window.

Switch Between Windows Using Selenium Python – Full Code

Switch Between Windows Selenium Python
Switch Between different Windows using Selenium Python API

The WebDriver library provides a simple method to address our need to shift from one browser window to another. However, there are two of them that you have to call accordingly.

The newer one: switch_to.window(window_handle) and the older version: switch_to_window(window_handle) . The choice to call them depends on the version of Selenium you are using. You can call these from your code using the following syntax.

  1. switch_to_window(window_handle): This was the syntax used in older versions of Selenium (pre-3.0). If you are working with an older version of Selenium, you should use this syntax.
win_handle = "your_window_handle"
web_driver.switch_to_window(win_handle)
  1. switch_to.window(window_handle): This is the correct syntax for newer versions of Selenium (3.0 and later). If you are using a relatively recent version of Selenium, it’s better to use this syntax.
win_handle = "your_window_handle"
web_driver.switch_to.window(win_handle)

The Webdriver library has a system in place to inspect all calls coming from the browser and its windows.

Selenium Python code to switch between windows

In this section, we’ll demonstrate how easily you achieve the transitioning of Windows in the Firefox web browser.

Now, refer to the example and the code to learn how it is working. In this, we used the newer method to switch between windows. You can do the same with Google Chrome, however, you will need to use the Chrome driver. We used some dummy websites to illustrate the desired workflow.

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

# Set up the doj (driver)
doj = webdriver.Firefox()
doj.maximize_window()

# Open the first website
doj.get("https://www.example.com")

# Get the first window handle
w1 = doj.window_handles[0]
t1 = doj.title
print(t1)

# Open a new window for another website
doj.execute_script("window.open('https://www.example.org', 'new window')")

# Get the second window handle
w2 = doj.window_handles[1]

# Switch to the new window
doj.switch_to.window(w2)

# Wait for the window to load
WebDriverWait(doj, 10).until(EC.title_contains("New Window Title"))

t2 = doj.title
print(t2)

# Compare titles
if t1 != t2:
    print('Switched to the second website as the titles do not match.')
else:
    print('Control did not switch to the new window.')

# Add a delay before switching back to the original window
time.sleep(3)

# Switch back to the original window
doj.switch_to.window(w1)

# Wait for the title of the original window to load
WebDriverWait(doj, 10).until(EC.title_contains("Original Window Title"))

# Verify that the titles now match
if t1 == doj.title:
    print('Returned to the parent window. Titles now match.')

print(doj.title)

# Close the doj
doj.quit()

In this example, we show you how to use Selenium with Python for web automation.

Also Check: Using Switch Case in Python

About the code to switch between windows

  1. Open the first window: This is the first step in the script, and it is straightforward. The code opens a Firefox browser window and navigates to a dummy site example.com.
  2. Get the window handles: This step is important because it allows the script to keep track of the windows that it has to use.
  3. Open a new window: This step opens a 2nd browser window and switches to the dummy site example.org by callingexecute_script() .
  4. Get the handle of a new window: This step is similar to step 2, but it gets the window handle of the second window and stores it in the variable win2.
  5. Switch to the new child window: This step switches the focus of the script to the second window. The code calls switch_to.window() to do this.
  6. Add an explicit wait: This step is important because it ensures that the script does not continue until the second window has fully loaded. The code uses the WebDriverWait class to wait for this purpose.
  7. Compare and verify that the window titles don’t match: This step compares the titles of the two windows and prints a message if it fails.
  8. Add a few seconds of wait before switching back: This step adds a brief pause. It ensures that the script has enough time to switch back to the main window.
  9. Switch back to the original window: This step switches the focus of the script back to the original window. The code uses the switch_to.window() method to do this.
  10. Add an explicit wait: This step is similar to step 6 to ensure the script waits enough to move to the original window.
  11. Verify the titles match: This step compares the titles of the two windows again and prints a message if it fails.
  12. Close the driver: This step closes the browser driver and quits the script.

Point-by-point summary

Here is a point-by-point summary of your code, considering my last reply:

  • Open the first window and get the window handle.
  • Open a new window and get the window handle.
  • Switch to the new window and wait for it to load. It is a good coding practice to use WebDriverWait.
  • Compare the titles of the two windows to verify that the switch was successful.
  • Wait a few seconds before switching back to the original window.
  • Switch back to the original window and wait for it to load.
  • Compare the titles of the two windows again to verify that the switch was successful.
  • Close the browser driver.

This example is like a starting point to learn web automation. It’s handy for testers, developers, and anyone who wants to automate web stuff. The code shows smart waiting, handling windows right, and checking things properly to make strong and dependable automated tests.

Conclusion

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

Selenium makes it easy to work with multiple browser windows, tabs, and pop-ups. This guide helps you switch between them, interact with elements, and automate tasks. Keep practicing to become a skilled Selenium user!

For more updates on Selenium Python tutorials, do follow us on our social media accounts. It will ensure you get free access to all our future resources.

Best,

TechBeamers

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Navigation Selenium Python Tutorial Web Page Navigation in Selenium Python
Next Article Switch Between IFrames Selenium Python How to Switch Between IFrames Using Selenium Python

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x