Selenium(14):JS弹框的操作

alert/confirm/prompt处理:

  WebDriver中处理原生JS的 alert、confirm以及prompt非常方便。

  具体思路是使用switch_to.alert()方法定位到当前的 alert/confirm/prompt (这里注意当前页面只能同时含有一个控件,如果多了会报错的,所以这就需要一一处理了),然后在调用Alert的方法进行操作;

Alert提供了以下几个方法:

text:返回alert/confirm/prompt中的文字内容
accept: 点击确认按钮
dismiss: 点击取消按钮如果有取消按钮的话
send_keys: 向prompt中输入文字

备注:send_keys这个方法在chromedriver中输入后不会显示。并且要和accept联合使用才有效

代码如下:

import os
import time
from selenium import webdriver
from selenium.webdriver.common.by import By


current_path = os.path.dirname(os.path.abspath(__file__))  # 当前路径
driver_path = os.path.join(current_path,'../webdriver/chromedriver.exe')  # driver路径
pages_path = os.path.join(current_path,'../pages/element_samples.html')  # 本地网页路径
driver = webdriver.Chrome(executable_path=driver_path)  # Firefox,Ie等
driver.get('file://%s'%pages_path)  # 本地网页打开file://  打开部署好的站点http://

# alert弹框
driver.find_element(By.XPATH,'//input[@name="alterbutton"]').click()
time.sleep(2)
text = driver.switch_to.alert.text  # 获取弹框的文本
driver.switch_to.alert.accept()  # 点击确定
print( text )

# confirm弹框
driver.find_element(By.XPATH,'//input[@name="confirmbutton"]').click()
time.sleep(2)
driver.switch_to.alert.dismiss()  # 点击取消
text1 = driver.switch_to.alert.text  # 获取弹框的文本
time.sleep(2)
driver.switch_to.alert.accept()  # 点击确定
print( text1 )

# prompt弹框
# 备注:send_keys这个方法在chromedriver中输入后不会显示。并且要和accept联合使用才有效
driver.find_element(By.XPATH,'//input[@name="promptbutton"]').click()
time.sleep(2)
driver.switch_to.alert.send_keys('python')  # 必须send_keys和accept()联合使用才生效
driver.switch_to.alert.accept()  # 点击确定
driver.switch_to.alert.accept()  # 再点击确定

 

posted @ 2021-11-26 16:11  奔跑在路上you  阅读(202)  评论(0编辑  收藏  举报