Switching windows or tabs is also possible from Python selenium code. The example below uses the selenium module and web driver.
This should work for all the supported web browsers including Chrome, Firefox, IE and all the others.
Practice now: Test your Python skills with interactive challenges
switch to window
selenium switch to window
Before you start, install the selenium module, the Web Driver for your browser and the browser itself. The way this works is that the web driver controls the browser, and Python communicates with the web driver.
The selenium switch to window code shown below. It starts firefox, opens a webpage, then a new tab and window with different web sites.
# -*- coding: utf-8 -*-
from selenium import webdriver
import time
browser=webdriver.Firefox()
browser.get("https://www.reddit.com")
browser.execute_script("window.open()")
print(browser.window_handles)
browser.switch_to_window(browser.window_handles[1])
browser.get("https://www.youtube.com")
time.sleep(1)
browser.switch_to_window(browser.window_handles[0])
browser.get("https://python.org")
#browser.close()

First it opens the web browser this way:
browser=webdriver.Firefox()
browser.get("https://www.reddit.com")
Then it opens a new tab and switches to that tab.
print(browser.window_handles)
browser.switch_to_window(browser.window_handles[1])
In the new tab it opens new url
time.sleep(1)
Then it switchse back to the first tab
browser.switch_to_window(browser.window_handles[0])
Practice now: Test your Python skills with interactive challenges