alter只有确定,confirm会有确定和取消,prompt可以输入一些信息
from selenium.webdriver.support.select import Select
from selenium import webdriver
from selenium.webdriver.common.by import By
from time import sleep
from selenium.webdriver.common.alert import Alert
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver import ActionChains
driver = webdriver.Chrome()
wait = WebDriverWait(driver, 5)
driver.get('https://selenium.dev/selenium/web/alerts.html')
sleep(2)
def alert1(driver):
# 点击弹窗
driver.find_element(By.ID, "alert").click()
# driver.find_element(By.ID, "empty-alert").click()
sleep(1)
# 等待显示
alert = wait.until(ec.alert_is_present())
# 获取文本信息
text = alert.text
print(text)
sleep(1)
# 点击确认
alert.accept()
alert1(driver)
def confirm1(driver):
# 点击弹窗
driver.find_element(By.ID, "confirm").click()
# 等待显示
confirm = wait.until(ec.alert_is_present())
# 点击取消
sleep(1)
confirm.dismiss()
confirm1(driver)
def prompt1(driver):
# 点击弹窗
driver.find_element(By.ID, "prompt").click()
# 等待显示
prompt = wait.until(ec.alert_is_present())
sleep(1)
# 输入文字
# alert_prompt = driver.switch_to.alert # 方法一
alert_prompt = Alert(driver) # 方法二
alert_prompt.send_keys('test1') #chrome 不会显示,但会传输
sleep(1)
alert_prompt.accept()
prompt1(driver)
def iframe(driver):
#滑动到位
iframe = driver.find_element(By.NAME, "iframeWithAlert")
ActionChains(driver).scroll_to_element(iframe).perform()
# swith_to;点击弹窗
driver.switch_to.frame("iframeWithAlert") # 可以直接输入id和name,或者driver.switch_to.frame(driver.find_elements(By.TAG_NAME, "iframe")[0])
driver.find_element(By.LINK_TEXT, "click me").click()
# 等待显示
sleep(2)
alert_iframe = wait.until(ec.alert_is_present())
alert_iframe.accept()
sleep(1)
driver.switch_to.default_content()
iframe(driver)
def turn_window(driver):
driver.get('http://novel.hctestedu.com/')
wait = WebDriverWait(driver, 10)
# 存储原始窗口句柄
hd = driver.current_window_handle
# print(hd)
# 检查是否只有一个窗口
assert len(driver.window_handles) == 1 # 只有一个窗口
# 打开新页签
driver.find_element(By.LINK_TEXT, '作家专区').click()
# 等待新窗口打开
wait.until(ec.number_of_windows_to_be(2))
all_handle = driver.window_handles
# print("all handles: ", str(all_handle))
"""
# 切换方式1:循环执行,直到找到新的
for i in all_handle:
if i != hd:
driver.switch_to.window(i)
break
"""
# 切换方式2:切换到最新打开窗口(列表操作)
driver.switch_to.window(all_handle[-1])
sleep(2)
print("当前窗口句柄", driver.current_window_handle)
# 等待加载完成
wait.until(ec.title_is('会员登录_读书屋'))
sleep(2)
# 关闭当前页or窗口
driver.close()
sleep(2)
# 切回之前的窗口
driver.switch_to.window(hd)
turn_window(driver)
with webdriver.Chrome() as driver:
print(“这个方法可以确保退出杀干净程序”)