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.

Related course:

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# -*- 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()

selenium switch to window

First it opens the web browser this way:

1
2
browser=webdriver.Firefox()
browser.get("https://www.reddit.com")

Then it opens a new tab and switches to that tab.

1
2
print(browser.window_handles)
browser.switch_to_window(browser.window_handles[1])

In the new tab it opens new url

1
time.sleep(1)

Then it switchse back to the first tab

1
browser.switch_to_window(browser.window_handles[0])

If you are new to selenium, then I highly recommend this book.

Download examples