Get focus on the new window in Selenium Webdriver and Python

17,417

Solution 1

You will need to use the .switchTo(windowHandle); command to access your second window.

Before opening the second window - get the windowHandle of the open window:

String mainWindow = driver.getWindowHandle();

Then do your action that opens the second window. Now you'll need to know the handle of the second windowand switch control to it:

Set<string> handles = driver.getWindowHandles();  
    for (String handle : handles) {
        if (!handler.equals(mainWindow)) {
            driver.switchTo(handle);
            break;
    }
}

Your actions for the second window will now happen in that second window. When you're finished and need to interact with the first window again: driver.switchTo().defaultContent();

Solution 2

This worked for me in Python:

another_window = list(set(driver.window_handles) - {driver.current_window_handle})[0]
driver.switch_to.window(another_window);
Share:
17,417
Alichino
Author by

Alichino

Updated on June 05, 2022

Comments

  • Alichino
    Alichino almost 2 years

    Using Selenium Webdriver in Python I am able to click on a button that opens a new browser window, but I have no idea how to change the focus onto the new window. I've searched all over the internet, but found nothing helpful. The problem is that the window doesn't have a title!

    What I need is the focus on the new window, so I can take a screenshot of its contents.

    Here is the bit of code around the button that opens the new window:

    enter image description here

    How to do that...?

  • Alichino
    Alichino over 9 years
    I had to translate it to Python, but it worked. Thanks!
  • Mark Rowlands
    Mark Rowlands over 9 years
    Sorry I didn't realise it was python, I missed the tag. Took me ages to remember how to do it in Java!