How to switch to new window in Selenium for Python?

I am working on selenium automation project using Python.

I am facing an issue, which is handling multiple browser windows.

Scenario is as follows. When I click a link on the home page, a new window opens. In the newly opened window I cannot perform any actions, because the focus is still on the home page web driver.

Can anybody show me how to change focus from the background window to the newly opened window?

A possible solution is driver.switch_to.window(), but it requires the window’s name. How to find out the window’s name? If this is a wrong way to do this, can anybody give some code examples to perform this action?

You can do it by using window_handles and switch_to_window method.

Before clicking the link first store the window handle as

window_before = driver.window_handles[0]

after clicking the link store the window handle of newly opened window as

window_after = driver.window_handles[1]

then execute the switch to window methow to move to newly opened window


and similarly you can switch between old and new window. Following is the code example

import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from import By

class GoogleOrgSearch(unittest.TestCase):

     def setUp(self):
         self.driver = webdriver.Firefox()

    def test_google_search_page(self):
         driver = self.driver
         window_before = driver.window_handles[0]
         print window_before
         window_after = driver.window_handles[1]
         print window_after

    def tearDown(self):

if __name__ == "__main__":