How to switch to new window in Selenium for Python? How to switch to new window in Selenium for Python? python python

How to switch to new window in Selenium for Python?


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 method to move to newly opened window

driver.switch_to_window(window_after)

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

import unittestfrom selenium import webdriverclass GoogleOrgSearch(unittest.TestCase):    def setUp(self):        self.driver = webdriver.Firefox()    def test_google_search_page(self):        driver = self.driver        driver.get("http://www.cdot.in")        window_before = driver.window_handles[0]        print window_before        driver.find_element_by_xpath("//a[@href='http://www.cdot.in/home.htm']").click()        window_after = driver.window_handles[1]        driver.switch_to_window(window_after)        print window_after        driver.find_element_by_link_text("ATM").click()        driver.switch_to_window(window_before)    def tearDown(self):        self.driver.close()if __name__ == "__main__":    unittest.main()


On top of the answers already given, to open a new tab the javascript command window.open() can be used.

For example:

# Opens a new tabself.driver.execute_script("window.open()")# Switch to the newly opened tabself.driver.switch_to.window(self.driver.window_handles[1])# Navigate to new URL in new tabself.driver.get("https://google.com")# Run other commands in the new tab here

You're then able to close the original tab as follows

# Switch to original tabself.driver.switch_to.window(self.driver.window_handles[0])# Close original tabself.driver.close()# Switch back to newly opened tab, which is now in position 0self.driver.switch_to.window(self.driver.window_handles[0])

Or close the newly opened tab

# Close current tabself.driver.close()# Switch back to original tabself.driver.switch_to.window(self.driver.window_handles[0])

Hope this helps.


window_handles should give you the references to all open windows.

this is what the documentation has to say about switching windows.