Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in DevOps and Agile by (19.4k points)

I am working on selenium automation project using Python.

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

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

1 Answer

0 votes
by (27.5k points)

Let me give you an example:

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

Since that is a current window, we can name it

main_page = driver.current_window_handle

If there is at least 1 window popup except for 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, after logging in apply the credentials. The window will disappear, but you have to come to the main page window and you are done.

driver.switch_to.window(main_page)

sleep(10)

If you are interested to learn Selenium on a much deeper level and want to become a professional in the testing domain, check out Intellipaat’s online Selenium course

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...