Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Selenium get current window handle

Selenium for Java and Ruby have methods to get current window handle.

For example, in Java it's pointed here.

In the same time Pythonic version of Selenium has no such method.

  1. Maybe it's inside, but I don't see it?
  2. If it's skipped, is it reasonable and how to make workaround for it?
like image 718
AlexKorovyansky Avatar asked Dec 25 '14 08:12

AlexKorovyansky


People also ask

How does Selenium handle current window?

The window handle is a unique identifier that stores the values of windows opened on a webpage and helps in window handling in Selenium. getWindowHandles( ) and getWindowHandles( ) handle windows in Selenium. The user has to switch from the parent window to the child window to work on them using switchTo( ) method.

Which method can be used to get the current handle of the window?

Get the handles of all the windows that are currently open using the command: Set<String> allWindowHandles = driver. getWindowHandles(); which returns the set of handles. Use the SwitchTo command to switch to the desired window and also pass the URL of the web page.

What is window handle in Selenium Python?

Get window handleIf your site opens a new tab or window, Selenium will let you work with it using a window handle. Each window has a unique identifier which remains persistent in a single session. You can get the window handle of the current window by using: Java. Python.


1 Answers

There is current_window_handle property available on the WebDriver instance:

driver.current_window_handle

Demo:

>>> from selenium import webdriver
>>>
>>> driver = webdriver.Chrome()
>>> driver.get('https://stackoverflow.com')
>>> 
>>> driver.current_window_handle
CDwindow-B22C1E54-977D-4B2A-8048-E9C73999E9C7

To get the name of the window in python but using javascript you can do this in python: ( I looked for this everywhere, but no answer was given for this)

window_title = driver.execute_script("return window.document.title") 

window_name = driver.execute_script("return window.name") # e.g. 'win1'
like image 152
alecxe Avatar answered Sep 30 '22 13:09

alecxe