[Python automated testing]: processing of pop-up windows

1. Background

  • Pop-up boxes on some pages, if you don’t deal with it, you can’t do follow-up operations

2. Classification of pop-up windows

2.1 Warning prompt pop-up window

  • [Description]: Contains prompt information and [Confirm] button
  • 【Operation】: 1. Obtain the content of the pop-up window; 2. Perform the "confirm" operation
  • 【Grammar Realization】
    • 1. Obtain the content of the pop-up window:driver.switch_to.alert.text
    • 2. Confirm the operation:driver.switch_to.alert.accept()
  • 【Code】
# 导包
from selenium import webdriver
from selenium.webdriver.common.by import By
# 导入鼠标操作的包
from selenium.webdriver.common.action_chains import ActionChains
# 导入显示元素等待的包
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

# 定义一个谷歌浏览器对象
driver = webdriver.Chrome()
# 打开百度首页
driver.get('https://www.baidu.com')

# 定位到页面的“设置”元素,并使得光标悬浮在该元素上
element1 = driver.find_element(By.CSS_SELECTOR, '#s-usersetting-top')
ActionChains(driver).move_to_element(element1).perform()
# 点击“设置”元素下拉框中“搜索设置”链接
driver.find_element(By.LINK_TEXT, '搜索设置').click()
# 弹窗的弹出需要时间,元素等待是需要考虑的重要问题
# 显式等待元素方法:等到指定的元素即可开始执行,否则抛出异常
element2 = WebDriverWait(driver, 2, 0.5).until(EC.presence_of_element_located((By.LINK_TEXT, '保存设置')), "保存设置元素定位不到")
# 在弹出的弹窗中点击“保存设置”链接
element2.click()

# 页面停留2秒钟,方便查看效果
time.sleep(2)

# 在弹出的警告弹窗中点击“确定”按钮
# 设置隐式等待
driver.implicitly_wait(2)
# 移到警告弹窗,获取弹窗内容,并点击“确认”
print(driver.switch_to.alert.text)
driver.switch_to.alert.accept()


# 退出浏览器
driver.quit()

2.2 Confirm pop-up window

  • [Description]: Contains prompt information and [Confirm] [Cancel] buttons
  • 【Operation】: 1. Obtain the content of the pop-up window; 2. Perform the "confirm" operation; 3. Perform the cancel operation
  • 【Grammar Realization】
    • 1. Obtain the content of the pop-up window:driver.switch_to.alert.text
    • 2. Confirm the operation:driver.switch_to.alert.accept()
    • 3. Perform the cancel operation:driver.switch_to.alert.dismiss()

2.3 Input information prompt pop-up window

  • [Description]: Contains prompt information, input information box and [Confirm] [Cancel] button
  • [Operation]: 1. Obtain the content of the pop-up window; 2. Enter information in the input box; 3. Perform the "confirm" operation; 4. Perform the cancel operation
  • 【Grammar Realization】
    • 1. Obtain the content of the pop-up window:driver.switch_to.alert.text
    • 2. Enter information in the input box:driver.switch_to.alert.send_keys()
    • 3. Confirm the operation:driver.switch_to.alert.accept()
    • 4. To cancel:driver.switch_to.alert.dismiss()

Guess you like

Origin blog.csdn.net/Lucifer__hell/article/details/129616100