85

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?

6 Answers 6

90

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 unittest
from selenium import webdriver

class 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()
Sign up to request clarification or add additional context in comments.

3 Comments

Following your code, I receive an IndexError: list index out of range when executing window_after = browser.window_handles[1]. What is wrong? See: stackoverflow.com/questions/45354850/…
@LucSpan I had the same issue, but using time.sleep(10) to wait for the other webpage to load solved this
driver.switch_to_window() is now depreciated. Replace it with driver.switch_to.window() to remove the warning
36

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 tab
self.driver.execute_script("window.open()")

# Switch to the newly opened tab
self.driver.switch_to.window(self.driver.window_handles[1])

# Navigate to new URL in new tab
self.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 tab
self.driver.switch_to.window(self.driver.window_handles[0])

# Close original tab
self.driver.close()

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

Or close the newly opened tab

# Close current tab
self.driver.close()

# Switch back to original tab
self.driver.switch_to.window(self.driver.window_handles[0])

Hope this helps.

1 Comment

switch_to_window is deprecated. Use switch_to.window
26

window_handles should give you the references to all open windows.

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

Comments

11

for eg. you may take

driver.get('https://www.naukri.com/')

since, it is a current window ,we can name it

main_page = driver.current_window_handle

if there are atleast 1 window popup except the current window,you may try this method and put if condition in break statement by hit n trial for the index

for handle in driver.window_handles:
    if handle != main_page:
        print(handle)
        login_page = handle
        break

driver.switch_to.window(login_page)

Now ,whatever the credentials you have to apply,provide after it is loggen in. Window will disappear, but you have to come to main page window and you are done

driver.switch_to.window(main_page)
sleep(10)

Comments

6

We can handle the different windows by moving between named windows using the “switchTo” method:

driver.switch_to.window("windowName")

<a href="somewhere.html" target="windowName">Click here to open a new window</a>

Alternatively, you can pass a “window handle” to the “switchTo().window()” method. Knowing this, it’s possible to iterate over every open window like so:

for handle in driver.window_handles:
    driver.switch_to.window(handle)

Comments

0
try:
    # Each browser window or tab opened by WebDriver is identified by a unique "handle".
    # Think of it like an ID string that Selenium uses internally to know which window
    handles = webdriver.window_handles

    # If there is at least one window handle available:
    if handles:
        # Switch to the first window (index 0).
        # This tells Selenium: "make this window the active one for all following commands."
        webdriver.switch_to.window(handles[0])  

    # assume one window
    # → This code assumes you only have a single window or tab open.
    #   If there are multiple, you'll need to pick the right one (e.g., handles[1], handles[2], etc.)
    #   or loop through handles to find the window with the URL/title you want.

    # simple way to implement into your code if it's a small service
    # → For small scripts or one-window cases, just grabbing handles[0] works fine.
    #   For larger apps, you might want to add logic to choose the correct handle.

    # exception can be handled if the url of the window cant be read

    # note: check if your server is running
    # → If the page is served from your local FastAPI/Flask/etc server,
    #   make sure that backend is running; otherwise Selenium may open a blank page
    #   or throw navigation timeouts.
except Exception as e:
    print("Error switching windows:", e) #can use webdriver.current_url  for sending a response 

1 Comment

Thank you for your interest in contributing to the Stack Overflow community. This question already has quite a few answers—including one that has been extensively validated by the community. Are you certain your approach hasn’t been given previously? If so, it would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers aren’t sufficient. Can you kindly edit your answer to offer an explanation?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.