Python+selenium 獲取瀏覽器視窗座標、控制代碼
阿新 • • 發佈:2019-02-01
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]) #切換到最新視窗的控制代碼