什么是瀏覽器窗口句柄?
當打開一個瀏覽器並打開了一個新標簽頁時,該標簽頁就會有一個句柄標識(句柄值)。直到你關閉了該標簽頁,該句柄標識(句柄值)才消失。
所以,當我們打開一個瀏覽器並打開了多個標簽頁時,關閉一個標簽頁不會影響其他標簽頁,就是因為每個標簽頁有了唯一的標識。
1、獲取當前標簽頁句柄:current_window_handle
示例:
from selenium import webdriver driver = webdriver.Firefox() # 打開百度 driver.get("https://www.baidu.com") # 獲取當前標簽頁的句柄值 c_handle = driver.current_window_handle print(type(c_handle)) print(c_handle)
運行結果如下:
<class 'str'> 18
我們可以看到,通過current_window_handle獲取到了當前標簽頁的屬性值,且該值的類型為字符串。
2,獲取瀏覽器所有標簽頁的句柄:window_handles
示例:
driver = webdriver.Firefox() # 打開百度 driver.get("https://www.baidu.com") # 打開網易門戶 js_new_window = "window.open('https://www.163.com')" driver.execute_script(js_new_window) # 獲取瀏覽器中所有標簽頁的句柄值 handles = driver.window_handles print(type(handles)) for handle in handles: print(handle)
執行結果如下:
<class 'list'> 18 4294967297
我們可以看到,window_handles返回的是一個列表,里面包含了所有的標簽頁的句柄。
3,切換句柄:switch_to.window()
傳參window_name,即傳入句柄值
我們看一下window()方法:
def window(self, window_name): """ Switches focus to the specified window. :Args: - window_name: The name or window handle of the window to switch to. :Usage: driver.switch_to.window('main') """ if self._driver.w3c: self._w3c_window(window_name) return data = {'name': window_name} self._driver.execute(Command.SWITCH_TO_WINDOW, data)
我們可以看到:window()方法接收參數,並執行command命令進行窗口切換
下面我們看一下切換窗口的示例:
from selenium import webdriver driver = webdriver.Firefox() # 打開百度 driver.get("https://www.baidu.com") # 打開網易門戶 js_new_window = "window.open('https://www.163.com')" driver.execute_script(js_new_window) # 獲取瀏覽器中所有標簽頁的句柄值 handles = driver.window_handles # 當前窗口句柄值 c_handle = driver.current_window_handle print("當前標簽頁句柄值:", c_handle) # 切換窗口 driver.switch_to.window(handles[1]) # 切換窗口后的句柄值 c1_handle = driver.current_window_handle print("切換窗口后的標簽頁句柄值:", c1_handle)
執行結果如下,我們可以看到當前窗口句柄值已經不同了,說明切換成功:
當前標簽頁句柄值: 18
切換窗口后的標簽頁句柄值: 4294967297
這個例子的執行表現過程為:打開瀏覽器並打開百度首頁->js打開網易門戶->獲取所有窗口句柄值->打印當前窗口句柄值->切換窗口->打印當前窗口句柄值(切換
后的窗口)》