'''
環境:
Python 3.8
selenium==3.141.0
urllib3==1.26.19
''''''
說明:
driver.current_window_handle # 返回當前窗口的句柄
driver.window_handles # 返回當前由driver啟動所有窗口句柄,是個列表
driver.switch_to.window(handle) # 根據 handle 切換窗口
'''
# -*- coding: UTF-8 -*-from selenium import webdriver
import time# 谷歌瀏覽器位置
CHROME_PATH = r'xxx\\chrome.exe'
# 谷歌瀏覽器驅動地址
CHROMEDRIVER_PATH = r'xxx\\chromedriver.exe'options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option("useAutomationExtension", False)
options.binary_location = CHROME_PATH
driver = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH, options=options)# 第一個窗口 打開百度
driver.get('https://www.baidu.com/')
time.sleep(3)
handle_baidu = driver.current_window_handle
print(handle_baidu) # CDwindow-E8B2BA11FBCE9C5FF7A39E34C8056B88
print(driver.title) # 百度一下,你就知道# 第二個窗口 打開 Bing
new_tab_url = 'https://cn.bing.com/'
driver.execute_script(f'window.open("{new_tab_url}", "_blank");')
# 確保第二個窗口打開
time.sleep(3)
# 獲取所有窗口句柄
handles = driver.window_handles
print(handles) # ['CDwindow-E8B2BA11FBCE9C5FF7A39E34C8056B88', 'CDwindow-8B22C4B42A61E59D68C384C9E4C6653B']# 切換到最新窗口
driver.switch_to.window(handles[-1])
print(driver.title) # 必應# 切換到 百度窗口
driver.switch_to.window(handle_baidu)
print(driver.title) # 百度一下,你就知道# 設置固定等待
time.sleep(50)
driver.quit()
'''
參考:
python自動化測試selenium(四)切換頁面、切換窗口
https://blog.csdn.net/u010835747/article/details/125501993
'''