多窗口切换
页面操作是点击连接,弹出新的窗口,在新窗口操作就需要切换窗口。
WebDriver提供的switch_to.windows()方法可以实现不同窗口之间的切换。
-
current_window_handle #获得当前窗口句柄
-
window_handles #返回所有窗口句柄到当前会话
-
switch_to.window() #切花相应的窗口,传窗口句柄
from selenium import webdriver import time driver = webdriver.Chrome() driver.get("https://www.baidu.com") driver.maximize_window() #点击贴吧 driver.find_element_by_xpath("//div[@id='s-top-left']/a[5]").click() print("当前url:" + driver.current_url) #获取所有窗口句柄 all_window = driver.window_handles #获取当前窗口句柄 search_window = driver.current_window_handle print("当前窗口句柄:" + search_window) #切换至贴吧窗口 for handle in all_window: if handle != search_window: driver.switch_to.window(handle) #切换至新窗口 print("当前url:" + driver.current_url) print("当前窗口句柄:" + driver.current_window_handle) time.sleep(2) driver.close() #回到首页窗口 driver.switch_to.window(search_window) print("当前url:" + driver.current_url) time.sleep(2) driver.quit()

浙公网安备 33010602011771号