yourwhat 2022-06-28 19:30 采纳率: 0%
浏览 262

python selenium 新窗口有alert,采用switch_to.window无法切换到新窗口确认alert

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。


  • 写回答

2条回答 默认 最新

报告相同问题?

问题事件

  • 创建了问题 6月28日

悬赏问题

  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示