首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >一个大问题:当使用时,不能接受警报,从第一个选项卡切换到第二个选项卡,后者在加载时会弹出警报。

一个大问题:当使用时,不能接受警报,从第一个选项卡切换到第二个选项卡,后者在加载时会弹出警报。
EN

Stack Overflow用户
提问于 2022-06-29 13:31:38
回答 1查看 72关注 0票数 0

这里是python代码。

  1. 通过单击第一个选项卡
  2. 中的一个按钮打开第二个选项卡,第二个选项卡在加载时弹出一个警报对话框,但无法找到警报。

代码语言:javascript
复制
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)内容

页面上有两个按钮。

代码语言:javascript
复制
<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)内容

必须小心,第二个标签将弹出警报时,加载!

代码语言:javascript
复制
<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>
EN

回答 1

Stack Overflow用户

发布于 2022-06-30 15:06:38

封锁我有一个新发现!但这是什么鬼东西!它对switch_to.window和switch_to.alert太困惑了!

这个上下文如下:使用selenium的python代码从第一个选项卡打开一个新选项卡,新选项卡在加载时弹出一个警报对话框。要接受此警报,必须切换到新选项卡,因为此时current_window_handle仍然指向第一个选项卡。所以使用代码

代码语言:javascript
复制
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

代码语言:javascript
复制
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可以找到第二个选项卡中的其他警报弹出!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72802293

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档