Python Selenium 获取浏览器窗口坐标与句柄的正确姿势
本文介绍在Python Selenium中获取浏览器窗口坐标和句柄的方法。针对get_window_rect()可能出现的“Command not found”错误,推荐使用get_window_position()和get_window_size()分别获取坐标与大小。同时演示如何通过driver.window_handles获取所有句柄,并利用switch_to.window()进行窗口切换,适用于多窗口操作场景。
1.0 获取浏览器窗口坐标
在Python的Webdriver.py文件中,定义了get_window_rect()函数,该函数旨在获取窗口的坐标及长宽信息。然而在实际使用中,有时会遇到“Command not found”的错误提示。同样地,set_window_rect()函数也可能面临相同的问题。
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']
不过,Webdriver.py文件还定义了get_window_position()函数和get_window_size()函数。我们可以利用这两个函数分别获取窗口的坐标和大小,从而避免依赖win32gui模块。
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 获取窗口句柄
handle = driver.current_window_handle #获取当前窗口句柄 handles = driver.window_handles #获取所有窗口句柄
切换窗口句柄可以使用以下方法:
dr.switch_to.window(handle) #其中handle为获取到的窗口句柄
假设handles为获取到的所有窗口句柄列表,则handles为一个list,可使用访问list的方法读取句柄。
dr.switch_to.windows(handles[0]) #切换到第一个窗口的句柄 dr.switch_to.windows(handles[-1]) #切换到最新窗口的句柄
以上这篇Python+selenium 获取浏览器窗口坐标、句柄的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持本站。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









