这里是python代码。
import sys
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get('d:\\testalert\\testalert.html')
driver.find_element(By.XPATH, '/html/body/input[2]').click() # open the second tab
driver.switch_to.window(driver.window_handles[0]) # if don't switch to first handle, but directly switch to the second, code will dead.
driver.switch_to.window(driver.window_handles[1]) # now current window handle is the second handle
time.sleep(5)
driver.switch_to.alert.accept()
driver.quit()
sys.exit(0)下面是第一个html文件(testalert.html)内容
页面上有两个按钮。
<html>
<head>
<script type="text/javascript">
function display_alert_current_window()
{
alert("I am an alert box!!")
}
function display_alert_another_window()
{
window.open("testalert2.html")
}
</script>
</head>
<body>
<input type="button" onclick="display_alert_current_window()" value="Display alert box in current window" />
<input type="button" onclick="display_alert_another_window()" value="Display alert box in another window" />
</body>
</html>下面是第二个html文件(testwart2.html)内容
必须小心,第二个标签将弹出警报时,加载!
<html>
<head>
<title>title2</title>
<script type="text/javascript">
function display_alert()
{
alert("I am an alert box!!")
}
</script>
</head>
<body onload="display_alert();">
<input type="button" onclick="display_alert()" value="Display alert box" />
</body>
</html>发布于 2022-06-30 15:06:38
封锁我有一个新发现!但这是什么鬼东西!它对switch_to.window和switch_to.alert太困惑了!
这个上下文如下:使用selenium的python代码从第一个选项卡打开一个新选项卡,新选项卡在加载时弹出一个警报对话框。要接受此警报,必须切换到新选项卡,因为此时current_window_handle仍然指向第一个选项卡。所以使用代码
driver.switch_to.window(driver.window_handles[1]) # to the second tab
driver.switch_to.alert.accept() # to accept the alert但是,switch_to.alert会致命等待,或者打印(driver.current_window_hanle)也会致命等待!为甚麽这样呢?如果不使用switch_to.alert或access current_window_handle,一切都好!我们可以使用pynput.keyboard模拟Enter键来接受警报!
以下是答案:
再次感谢https://www.cnpython.com/qa/1339790
driver.switch_to.window(window_handles[0])
driver.switch_to.window(window_handles[1])
from pynput.keyboard import Key, Controller
import time
keyboard = Controller()
time.sleep(2)
keyboard.press(Key.enter)
keyboard.release(Key.enter)它能正常工作!接受原始警报后,switch_to.alert可以找到第二个选项卡中的其他警报弹出!
https://stackoverflow.com/questions/72802293
复制相似问题