第一种方法:
使用场景: 打开多个窗口,需要定位到新打开的窗口
使用方法:
# 获取打开的多个窗口句柄 windows = driver.window_handles # 切换到当前最新打开的窗口 driver.switch_to.window(windows[-1])
第二种方法:
# 获得打开的第一个窗口句柄 window_1 = driver.current_window_handle # 获得打开的所有的窗口句柄 windows = driver.window_handles # 切换到最新的窗口 for current_window in windows: if current_window != window_1: driver.switch_to.window(current_window)
1、第一种方法比较简单,能提升整体代码的性能
2、第二种方法是大家最常用的方法,比较容易理解
使用js切换窗口
from selenium import webdriver import time #设置变量 url="http://www.baidu.com" #打开浏览器 br=webdriver.Chrome() br.maximize_window() #打开百度 br.get(urla) #通过JS打开新窗口 js='window.open("https://blog.csdn.net");' br.execute_script(js) time.sleep(3) #获取当前句柄(百度) handlea=br.current_window_handle #获取所有句柄 handles=br.window_handles print(handles) #获取csdn句柄 for handle in handles: if handle != handlea: handleb = handle # 输出CSDN句柄 print('switch to ', handleb) br.switch_to.window(handleb) time.sleep(3) #关闭CSDN界面 br.close() # 切换回百度窗口 print('switch Baidu ',handlea) br.switch_to.window(handlea) time.sleep(3) #关闭浏览器 br.quit()