Python+selenium to get the browser window coordinates handle method
- 2020-12-13 19:02:05
- OfStack
1.0 Gets browser window coordinates
The Webdriver.py file defines the get_window_rect() function, which gets the coordinates and size (length and width) of the window, but with the "Command not found" case. The set_window_rect() function is also 1.
def get_window_rect(self):
"""
Gets the x, y coordinates of the window as well as height and width of
the current window.
:Usage:
driver.get_window_rect()
"""
return self.execute(Command.GET_WINDOW_RECT)['value']
def set_window_rect(self, x=None, y=None, width=None, height=None):
"""
Sets the x, y coordinates of the window as well as height and width of
the current window.
:Usage:
driver.set_window_rect(x=10, y=10)
driver.set_window_rect(width=100, height=200)
driver.set_window_rect(x=10, y=10, width=100, height=200)
"""
if (x is None and y is None) and (height is None and width is None):
raise InvalidArgumentException("x and y or height and width need values")
return self.execute(Command.SET_WINDOW_RECT,
{"x": x, "y": y, "width": width, "height": height})['value']
However, the Webdriver.py file also defines the get_window_position() function and get_window_size() function, which you can use to get the coordinates and size of the window, respectively, without using the win32gui method.
def get_window_size(self, windowHandle='current'):
"""
Gets the width and height of the current window.
:Usage:
driver.get_window_size()
"""
command = Command.GET_WINDOW_SIZE
if self.w3c:
if windowHandle != 'current':
warnings.warn("Only 'current' window is supported for W3C compatibile browsers.")
size = self.get_window_rect()
else:
size = self.execute(command, {'windowHandle': windowHandle})
if size.get('value', None) is not None:
size = size['value']
return {k: size[k] for k in ('width', 'height')}
def get_window_position(self, windowHandle='current'):
"""
Gets the x,y position of the current window.
:Usage:
driver.get_window_position()
"""
if self.w3c:
if windowHandle != 'current':
warnings.warn("Only 'current' window is supported for W3C compatibile browsers.")
position = self.get_window_rect()
else:
position = self.execute(Command.GET_WINDOW_POSITION,
{'windowHandle': windowHandle})['value']
return {k: position[k] for k in ('x', 'y')}
2.0 gets a window handle
handle = driver.current_window_handle # Gets the current window handle
handles = driver.window_handles # Gets all window handles
Switch handles can be used
dr.switch_to.window(handle) # Among them handle Is the window handle to get
Assuming that handles is all the Windows obtained, then handles is 1 list and the handle can be read using the method that accesses list.
dr.switch_to.windows(handles[0]) # Switch to the first 1 Handle to a window
dr.switch_to.windows(handles[-1]) # Switch to the handle to the latest window