python+selenium八:Alert弹窗

时间:2021-01-29 00:34:52

此弹窗是浏览器自带的弹窗,不是html中的元素

python+selenium八:Alert弹窗

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
import time
from selenium.webdriver.support.select import Select

driver = webdriver.Firefox()
url = "https://www.baidu.com"
driver.get(url)
time.sleep(3)

mouse = driver.find_element("link text", "设置")
ActionChains(driver).move_to_element(mouse).perform()
time.sleep(0.5)
driver.find_element("link text", "搜索设置").click()
time.sleep(1)

# 先定位到下拉框
s = driver.find_element_by_id("nr")
Select(s).select_by_visible_text("每页显示20条")
s.click()
time.sleep(1)

python+selenium八:Alert弹窗

# 点击保存按钮,此时会弹出确认提示框
driver.find_element_by_class_name("prefpanelgo").click()
time.sleep(0.5)

python+selenium八:Alert弹窗

# 获取弹窗
a = driver.switch_to_alert()
# 或者
# a = driver.switch_to.alert
print(a.text) # 打印弹窗的文字内容

python+selenium八:Alert弹窗

1、accept() 弹框的确定按钮
a.accept() # 点确定按钮

python+selenium八:Alert弹窗

2、dismiss() 弹框的取消按钮
a.dismiss() # 点取消按钮

python+selenium八:Alert弹窗

3、弹框若有输入框,需输入内容
a.send_keys("xxxx")

python+selenium八:Alert弹窗