使用百度多窗口演示,见下面web UI自动化脚本:
1 from selenium import webdriver 2 # 之前的 executable_path 被重构到了 Service 函数里 3 # 出错更新,https://blog.csdn.net/m0_62298204/article/details/120802053 4 from selenium.webdriver.chrome.service import Service 5 import time 6 7 chrome_driver = Service(r"D:\Python\Python39\chromedriver.exe") 8 driver = webdriver.Chrome(service=chrome_driver) 9 time.sleep(3) 10 11 driver.maximize_window() 12 driver.get('http://www.baidu.com/') 13 # 定位方式出错更新,https://blog.csdn.net/m0_54510474/article/details/121090473 14 driver.find_element('xpath','//*[@id="s-top-left"]/a[1]').click() 15 # 这个时候还是在1窗口,打印了窗口1的title 16 print(driver.title) 17 18 # 获取当前窗口句柄 19 handle = driver.current_window_handle 20 print("当前的handle{}".format(handle)) 21 22 # 获取所有的窗口句柄 23 handles =driver.window_handles 24 print("当前的所有handles{}".format(handles)) 25 26 # 切换句柄,切换到窗口2 27 driver.switch_to.window(handles[1]) 28 29 # 打印窗口2的title 30 print("切换句柄后的title是:{}".format(driver.title)) 31 32 # 继续关闭当前窗口后,无法找窗口2,需要切回窗口1 33 driver.close() 34 time.sleep(3) 35 driver.switch_to.window(handle) 36 37 # 回到窗口1,打印了窗口1的title 38 print("切换句柄后的title是:{}".format(driver.title)) 39 40 time.sleep(3) 41 driver.quit()
演示结果:
1 百度一下,你就知道 2 当前的handleCDwindow-C0B92C8EB09D01F89D43B0EDB1E83B57 3 当前的所有handles['CDwindow-C0B92C8EB09D01F89D43B0EDB1E83B57', 'CDwindow-3B771162A8FF7FF2F0218327CE23B31C'] 4 切换句柄后的title是:百度新闻——海量中文资讯平台 5 切换句柄后的title是:百度一下,你就知道 6 7 Process finished with exit code 0
2022-4-24,笔记