本文共 1361 字,大约阅读时间需要 4 分钟。
在页面操作中,常常会遇到如alert、confirm、prompt等警告框。可以利用Selenium的switch_to.alert()
方法来定位这些弹框,并进行相应操作。以下是常用方法详情:
这些方法为用户提供了对警告框操作的灵活控制,能够满足日常开发需求。
from selenium import webdriverfrom selenium.webdriver import ActionChainsfrom selenium.webdriver.common.by import Byclass TestAlert: def setup(self): self.driver = webdriver.Chrome() self.driver.implicitly_wait(3) self.driver.maximize_window() def test_alert(self): # 打开目标网页 self.driver.get("https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable") # 切换到弹框所在的框架 self.driver.switch_to.frame("iframeResult") # 定位拖拽元素 draggable = self.driver.find_element(By.ID, 'draggable') droppable = self.driver.find_element(By.ID, 'droppable') # 拖拽操作 action = ActionChains(self.driver) action.click_and_hold(draggable).move_to_element(droppable).release().perform() # 等待弹框出现 sleep(3) # 接受警告框 self.driver.switch_to.alert.accept() # 切回默认内容框架 self.driver.switch_to.default_content() # 点击提交按钮 self.driver.find_element_by_id("submitBTN").click()
以上代码演示了如何通过Selenium处理页面中的警告框。操作流程包括:打开网页、定位元素、执行拖拽操作、接受警告框、最后点击提交按钮。整个流程简洁明了,便于理解和参考。
转载地址:http://esczk.baihongyu.com/