1.使用try-except捕获异常,如果弹窗出现,则使用switch_to.alert
方法切换到弹窗并处理它。
try:
WebDriverWait(driver, 10).until(EC.alert_is_present())
alert = driver.switch_to.alert
alert.accept()
print("Alert accepted")
except TimeoutException:
print("No alert")
2.如果弹窗是基于iframe实现的,可以使用switch_to.frame
方法切换到iframe中,处理完弹窗后再使用switch_to.default_content
方法回到主文档中。
iframe = driver.find_element_by_tag_name("iframe")
driver.switch_to.frame(iframe)
# 处理弹窗
driver.switch_to.default_content()
3.使用Alert
类处理JavaScript Alert对话框
alert = driver.switch_to.alert
alert.accept()
4.如果弹窗是基于模态框实现的,可以使用execute_script
方法使用JavaScript来关闭弹窗
driver.execute_script("$('#modal-dialog').modal('hide');")
需要注意的是,处理弹窗时需要避免出现死循环或卡死的情况。可以使用WebDriverWait
等等工具来设置弹窗的等待时间,以便在超时时间内处理掉弹窗。