在自动化测试过程中,点击某个连接后往往会打开另外的窗口,有时候我们需要回到之前的窗口,这时候就需要有相应的标识才能切换,下面就通过获取浏览器句柄来实现窗口的切换
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get("https://www.jianshu.com/u/125ddf84ee1d")
driver.implicitly_wait(3)
#获取当前窗口的句柄
h = driver.current_window_handle
print(h) # 打印首页句柄
driver.find_element_by_link_text("功能测试").click()
# 获取当前所以的句柄:window_handles
all_h = driver.window_handles
print(all_h) # 打印所有的句柄
# 方法一:
# 1.循环判断是否与首页句柄相等
# 2.如果不等,说明是新页面的句柄
# 3.获取的新页面句柄后,可以切换到新打开的页面上
# 4.打印新页面的title,看是否切换成功
# for i in all_h:
# if i != h:
# switch_to.window(i)切换到windowname为i的页面
# driver.switch_to.window(i)
# print(driver.title)
# 方法二:获取list里面的第二个
driver.switch_to.window(all_h[1])
print(driver.title)
# 关闭新窗口
# driver.implicitly_wait(3)
# driver.close()
# 切换到首页句柄
driver.switch_to.window(h)
# 打印当前的title
print((driver.title))
网友评论