The Wayback Machine - https://web.archive.org/web/20241009105354/https://www.geeksforgeeks.org/how-to-switch-to-new-window-in-selenium-for-python/
Open In App

How to switch to new window in Selenium for Python?

Last Updated : 15 Mar, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Selenium is the most used Python tool for testing and automation for the web. But the problem occurs when it comes to a scenario where users need to switch between windows in chrome. Hence, selenium got that cover as well. Selenium uses these methods for this task-

  • window_handles is used for working with different windows. It stores the window ids that are used for switching.
  • switch_to.window method is used for switching between the windows with the help of window_handles ids.

Steps to cover:

  • Set up the URL and import selenium

Python3




# import modules
from selenium import webdriver  
import time  
  
# provide the path for chromedriver
PATH = "C:/chromedriver.exe"  
  
# pass on the path to driver for working
driver = webdriver.Chrome(PATH)  


  • Get the website URL and click on the link which opens in a new window. And switch between them.

Python3




# Open login yahoo for sample url
driver.get("https://login.yahoo.com/")  
  
# print title of yahoo window
print("First window title = " + driver.title)
  
# Clicks on privacy and it opens in new window
driver.find_element_by_class_name("privacy").click()
  
# switch window in 7 seconds
time.sleep(7)  
  
# window_handles[1] is a second window
driver.switch_to.window(driver.window_handles[1])
  
# prints the title of the second window
print("Second window title = " + driver.title)
  
# window_handles[0] is a first window
driver.switch_to.window(driver.window_handles[0])
  
# prints windows id
print(driver.window_handles)  


Output:

First window title = Yahoo
Second window title = Welcome to the Verizon Media Privacy Policy | Verizon Media Policies
['CDwindow-F25D48D2602CBD780FB2BE8B34A3BEAC', 'CDwindow-A80A74DFF7CCD47F628AF860F3D46913']

Explanation:

The program will first open yahoo then open privacy on yahoo in a new tab then again switch back to the yahoo tab in 7 seconds i.e first window.

Optional Case: If the user needs to open a new window and switch between them.

  • execute_script is a method for passing JavaScript as a string
  • window.open() is a method for opening the new window

Example 1:

Python3




# Open the new window
driver.execute_script("window.open()")
  
# window switch to new 3rd window
driver.switch_to.window(driver.window_handles[2])
  
# get the new url in window 3
  
# print the 3rd window title
print(driver.title)


Output:

GeeksforGeeks | A computer science portal for geeks

Explanation:

The program enables to open a new window with get() method having parameter as geeks for geeks URL and prints the title of that window.

Example 2:

Python3




# import modules
from selenium import webdriver
import time
  
# assign path and driver
PATH = "C:/chromedriver.exe"
driver = webdriver.Chrome(PATH)
  
# assign URL
print("First window title = " + driver.title)
  
# switch to new window
driver.find_element_by_class_name("privacy").click()
print(driver.window_handles)
driver.switch_to.window(driver.window_handles[1])
print("Second window title = " + driver.title)
  
# switch to new window
driver.execute_script("window.open()")
print(driver.window_handles)
driver.switch_to.window(driver.window_handles[2])
print(driver.title)


Output:

First window title = Yahoo

[‘CDwindow-3D8EFAF1BC9A66342F78731C64C802BD’, ‘CDwindow-B6ADD61824FA954B7E52A9844D304C34’]

Second window title = Welcome to the Verizon Media Privacy Policy | Verizon Media Policies

[‘CDwindow-3D8EFAF1BC9A66342F78731C64C802BD’, ‘CDwindow-B6ADD61824FA954B7E52A9844D304C34’, ‘CDwindow-3176B13D77F832E4DEC6869134FECD1D’]

GeeksforGeeks | A computer science portal for geeks

Explanation:

The script does the following:

  1. Opens yahoo and prints the title.
  2. Opens the privacy from yahoo and prints the title.
  3. Opens the new window and opens geeks for geeks on it and prints the title.


Previous Article
Next Article

Similar Reads

How to Switch between Window using Selenium in Python?
Selenium is an effective device for controlling an internet browser through the program. It is purposeful for all browsers, works on all fundamental OS and its scripts are written in numerous languages i.e Python, Java, C#, etc, we can be running with Python. It's miles fantastically viable that we open a massive range of windows. Each window might
2 min read
How to access popup login window in selenium using Python
Many websites use sign-in using social media to make the login process easy for users. In most cases, if the button is clicked then a new popup window is opened where the user has to enter their user credentials. Manually one can switch windows in a browser and enter the required credentials to log in. But in case of unattended web access using a w
3 min read
Open a new Window with a button in Python-Tkinter
Python provides a variety of GUI (Graphic User Interface) such as PyQt, Tkinter, Kivy and soon. Among them, tkinter is the most commonly used GUI module in Python since it is simple and easy to learn and implement as well. The word Tkinter comes from the tk interface. The tkinter module is available in Python standard library.Note: For more informa
3 min read
PyQtGraph – Getting Window Flags of Plot Window
In this article we will see how we can get window flags of the plot window in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) an
3 min read
PyQtGraph – Setting Window Flag to Plot Window
In this article we will see how we can set window flag to the plot window in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and
3 min read
Python | Switch widget in Kivy
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. ???????? Kivy Tutorial - Learn Kivy with Examples. Switch widget: The Switch widget is active or inactive, as a me
5 min read
Python | Switch widget in Kivy using .kv file
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. ???????? Kivy Tutorial - Learn Kivy with Examples. Switch widget: The Switch widget is active or inactive, as a me
4 min read
Create switch with Python-kivymd
In this article, we will see how to add the switch in our application using KivyMD in Python. MDSwitch: The switch is a kind of toggle button mostly used in android apps to on/off features.Its looks as: Installation: To install the modules type the below command in the terminal. pip install kivy pip install kivymd Method 1: Using kv language: Step
4 min read
Alternatives to Case/Switch Statements in Python
In many programming languages, the case or switch statement is a control flow mechanism that allows a variable to be tested for equality against a list of values, with each value associated with a block of code to be executed. However, Python does not have a built-in case or switch statement. Instead, Python developers use various alternative struc
3 min read
Switch Case in Python (Replacement)
In this article, we will try to understand Switch Case in Python (Replacement). What is the replacement of Switch Case in Python?Unlike every other programming language we have used before, Python does not have a switch or case statement. To get around this fact, we use dictionary mapping. Method 1: Switch Case implement in Python using Dictionary
5 min read
Tkinter Application to Switch Between Different Page Frames
Prerequisites: Python GUI – tkinter Sometimes it happens that we need to create an application with several pops up dialog boxes, i.e Page Frames. Here is a step by step process to create multiple Tkinter Page Frames and link them! This can be used as a boilerplate for more complex python GUI applications like creating interfaces for Virtual Labora
6 min read
On/Off Toggle Button Switch in Tkinter
Prerequisite: Tkinter Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. In this article, we wi
2 min read
Switch case in R
Switch case statements are a substitute for long if statements that compare a variable to several integral values. Switch case in R is a multiway branch statement. It allows a variable to be tested for equality against a list of values. Switch statement follows the approach of mapping and searching over a list of values. If there is more than one m
2 min read
Selenium Python Tricks
Selenium: Selenium Python bindings provide a convenient API to access Selenium Web Driver like Firefox, Chrome, etc. What is webdriver? Selenium WebDriver is an automation testing tool. When I say automation, it means it automates test scripts written in Selenium. Webdriver Install Chrome: https://sites.google.com/a/chromium.org/chromedriver/downlo
3 min read
Selenium Base Mini Project Using Python
Project Description:-Here, we're going to study a simple SMS bomber trick (for amusing and educational purpose). Selenium is a free tool for automated trying out across exceptional browsers. In this tutorial, we will learn how to ship mechanically range of unsolicited mail SMS for given variety of frequency and interval. Requirement: You need to in
2 min read
Get all text of the page using Selenium in Python
As we know Selenium is an automation tool through which we can automate browsers by writing some lines of code. It is compatible with all browsers, Operating systems, and also its program can be written in any programming language such as Python, Java, and many more. Selenium provides a convenient API to access Selenium WebDrivers like Firefox, IE,
3 min read
Close specific Web page using Selenium in Python
Prerequisites: Selenium Basics, Selenium close() and quit() Selenium is a powerful tool for controlling web browsers through programs and performing browser automation. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python. The close() meth
2 min read
Download Instagram Posts Using Python Selenium module
In this article, we will learn how we can download Instagram posts of a profile using Python Selenium module. Requirements:Google Chrome or FirefoxChrome driver(For Google Chrome) or Gecko driver(For Mozilla Firefox)Selenium package: It is a powerful tool for controlling a web browser through the program. It is functional for all browsers, works on
7 min read
Scrape and Save Table Data in CSV file using Selenium in Python
Selenium WebDriver is an open-source API that allows you to interact with a browser in the same way a real user would and its scripts are written in various languages i.e. Python, Java, C#, etc. Here we will be working with python to scrape data from tables on the web and store it as a CSV file. As Google Chrome is the most popular browser, to make
3 min read
Like instagram pictures using Selenium | Python
In this article, we will learn how can we like all the pictures of a profile on Instagram without scrolling and manually clicking the buttons. We will be using Selenium to do this task. Packages/Software needed: 1. Python 3 2. Chromedriver compatible with the existing chrome version (download chromedriver) 3. Google chrome 4. Selenium package (pip
3 min read
Python - Opening links using Selenium
Selenium is a powerful tool for controlling the web browser through the program. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python. Selenium Python bindings provide a convenient API to access Selenium WebDrivers like Firefox, Ie, Chrome
2 min read
How to take screenshot using Selenium in Python ?
Selenium offers a lot of features and one of the important and useful feature is of taking a screenshot. In order to take a screenshot of webpage save_screenshot() method is used. save_screenshot method allows user to save the webpage as a png file. Syntax : driver.save_screenshot("image.png") Argument : filename or the full path you wish to save y
1 min read
How to use close() and quit() method in Selenium Python ?
While doing stuff with selenium multiple browsers with multiple tabs will normally opens in order to close these tabs close() and quit() methods are used. close() method is used to close the current browser window on which the focus is set, on the other hand quit() method essentially calls the driver.dispose method that successively closes all the
2 min read
How to get title of a webpage using Selenium in Python?
The title method is used to retrieve the title of the webpage the user is currently working on. It gives the title of the current webpage loaded by the driver in selenium, if webpage has no title a null string will be returned. Webpage title :A page title, also known as a title tag, is a short description of a webpage and appears at the top of a br
2 min read
How to get current_url using Selenium in Python?
While doing work with selenium many URL get opened and redirected in order to keeping track of URL current_url method is used. The current_url method is used to retrieve the URL of the webpage the user is currently accessing. It gives the URL of the current webpage loaded by the driver in selenium. URL : URL is the abbreviation of Uniform Resource
2 min read
Python | page_source method in Selenium
page_source method is used retrieve the page source of the webpage the user is currently accessing. The main use of this method to find something in the page source like finding any data or keyword. Page source : The source code/page source is the programming behind any webpage. Syntax : driver.page_source Argument : It takes no argument. Return va
1 min read
Python - find_element() method in Selenium
While performing any action on a web page using selenium, there is need of locators to perform specific tasks. Locators in web page are used to identify unique elements within a webpage. Web elements could be anything that the user sees on the page, such as title, table, links, buttons, toggle button, or any other HTML element. In order to find ele
2 min read
Writing Tests using Selenium Python
Selenium's Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. Through Selenium Python API you can access all functionalities of Selenium WebDriver in an intuitive way. This article illustrates about how to use Selenium Python
2 min read
Navigating links using get method - Selenium Python
Selenium's Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. Through Selenium Python API you can access all functionalities of Selenium WebDriver in an intuitive way. This article illustrates about how to use Selenium Python
2 min read
find_element(By.Name) driver method - Selenium Python
Selenium's Python Module is built to perform automated testing with Python. Selenium Python bindings provide a simple API to write functional/acceptance tests using Selenium WebDriver. After you have installed selenium and checked out - Navigating links using get method, you might want to play more with Selenium Python. After one has opened a page
3 min read
Practice Tags :