[selenium] 关闭 alert 弹框

关闭 alert 弹框

当弹出 alert 框时,可以运用driver.switch_to.alert.accept()来关闭

代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
 <button onclick="alert('hehe')">alert</button>
</body>
</html>

将上述代码保存为alert.html

#!/usr/bin/env python
# coding: utf8
import os.path
import time

from selenium import webdriver

file_path = "file:///" + os.path.abspath("alert.html")
driver = webdriver.Chrome()
driver.get(file_path)

button = driver.find_element_by_tag_name("button")
button.click()

time.sleep(2)
driver.switch_to.alert.accept()

time.sleep(2)

driver.quit()