Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get focus on the new window in Selenium Webdriver and Python

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...?

like image 265
Alichino Avatar asked May 02 '26 15:05

Alichino


1 Answers

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();

like image 200
Mark Rowlands Avatar answered May 04 '26 03:05

Mark Rowlands



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!