有时候自动化测试需要打开多个标签页,在不同标签页之间切换并且测试功能,需要用到handle.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : handle.py
# Date : 2020/1/26 20:46
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from time import sleep
# 实例化driver
with webdriver.Chrome() as driver:
# 打开火狐主页
driver.get("https://home.firefoxchina.cn/")
# 显式等待
wait = WebDriverWait(driver, 10)
# 获得当前所在标签页的handle
original_window = driver.current_window_handle
# 检查只有一个打开的标签页
assert len(driver.window_handles) == 1
# 点击网页中的百度链接,会在新的标签页打开百度主页
wait.until(EC.presence_of_element_located((By.XPATH, '//li[@sid="375"]/a'))).click()
# driver.find_element_by_link_text("百 度").click()
# 等待新标签页的打开
wait.until(EC.number_of_windows_to_be(2))
# 循环所有handles,如果handle不是当前标签页的,就切换到当前标签页
for window_handle in driver.window_handles:
if window_handle != original_window:
driver.switch_to.window(window_handle)
break
# 等待新标签页加载内容,确认标题
wait.until(EC.title_is("百度一下,你就知道"))
# 切换回火狐主页标签
driver.switch_to.window(original_window)
# 关闭当前标签页
driver.close()
sleep(2)