selenium从一个窗口页面打开另一个窗口,新窗口会在页面加载的时候先弹框alert。想用switch_to.window切换到新窗口去确认alert,结果无法切换。
testalert.py
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() # 打开第二个页面
for window in driver.window_handles: # 现有两个窗口
print(window)
print('current window: ' + str(driver.current_window_handle)) # 仍指向第一个窗口
print('ready to switch to new window...')
driver.switch_to.window(driver.window_handles[1]) # failured 程序卡在这里,无法切换(手动确认alert后,可以继续执行)
print('current window: ' + str(driver.current_window_handle))
time.sleep(3)
driver.switch_to.alert.accept()
input('按任意键结束...')
print('accepted alert')
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>
testalert2.html
<html>
<head>
<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>
程序卡在driver.switch_to.window这里。
问题关键是无法切换到新窗口。
如何才能确认新窗口的弹框alert。