1. 切换到新的窗口页面里边操作
A. 循环遍历 driver.window_handles
B. driver.switch_to_window(handle) 方法切入新窗口
C. 检查该窗口的特点,是否为要切入的那个
2. 切换到最初的窗口
保存主窗口的handle然后switch_to
3. 关闭窗口:close方法
from selenium import webdriver
import time
driver = webdriver.Chrome(r"D:webdriverchromedriver_73.0.3683.68.exe")
driver.implicitly_wait(10)
driver.get("https://www.baidu.com/")
driver.find_element_by_id("kw").send_keys("太湖
")
time.sleep(2)
driver.find_element_by_xpath("//*[@id='1']/h3/a").click()
main_handle = driver.current_window_handle #当前窗口句柄
handles = driver.window_handles #所有窗口句柄
time.sleep(5)
print(handles)
for handle in handles:
print(handle)
driver.switch_to.window(handle)
if "太湖(江苏湖泊)" in driver.title:
driver.switch_to.window(handle)
print("跳转成功,当前网页url:",driver.current_url,"当前网页title:", driver.title)#【1.获取当前窗口的url,2.获取当前窗口的title】
driver.get_screenshot_as_file("taihu.png")#【3.获取当前页面截屏】
break
time.sleep(1)
driver.find_element_by_xpath("//*[@class='lemmaWgt-lemmaTitle-title']/a[3]").click()
driver.switch_to.window(main_handle)
driver.close()
input('...')
driver.quit()
结果:
['CDwindow-005C1777164F467C2E8EDCC9F5A506E2', 'CDwindow-99E965A41AB4DE16FBBDCCCD3EA858C0']
CDwindow-005C1777164F467C2E8EDCC9F5A506E2
CDwindow-99E965A41AB4DE16FBBDCCCD3EA858C0
跳转成功,当前网页url: https://baike.baidu.com/item/%E5%A4%AA%E6%B9%96/112298?fr=aladdin 当前网页title: 太湖(江苏湖泊)_百度百科
...