迷惑人的切换:switch_to定位window与alert。

新发现问题:迷惑人的切换:switch_to定位window与alert。python用selenium点击第一个页面中的按钮打开第二个页面,第二个页面在onload时弹alert,此时current_window_handle扔指向第一个窗口,为了确认第二个窗口的alert,需要切换到第二个窗口,采用switch_to.window(driver.window_handles[1]),发现在接下来的代码里不能用switch_to.alert或对current_window_handle的访问,否则就会卡在那里。这是为什么?
测试的页面文件与python代码见https://ask.csdn.net/questions/7750328/53835649?spm=1001.2014.3001.5504。重新开一个提问,是为了主要说明本次偶然发现的现象,请行家讲解。下面是本次的测试代码:
driver.switch_to.window(driver.window_handles[1])  # 下面开始测试
print('switch seccussfully')  # success
# driver.switch_to.window(driver.window_handles[1])  # success
# print(driver.window_handles[0])  # success
# print(driver.window_handles[1])  # success
# print(driver.current_window_handle) # failure
# driver.switch_to.alert.accept()  # failure
time.sleep(5)  # success

下面的代码是通过键盘模式确认第二个页面onload时的alert,在其后则可以正常用switch_to.alert确认后续的alert

from pynput.keyboard import Key, Controller
keyboard = Controller()
time.sleep(1)
keyboard.press(Key.enter)
keyboard.release(Key.enter)
print('确认原始alert')

i = 0
time.sleep(5)

while i < 5:
    i += 1
    print('自动弹窗口:' + str(i))
    driver.find_element(By.XPATH, '/html/body/input').click()
    time.sleep(1)
    try:
        driver.switch_to.alert.accept()
        print('确认次数:' + str(i))
    except:
        print('未检测到alert:' + str(i))
    time.sleep(5)
问题:这是为什么?是switch_to.window与alert有冲突?
自己的尝试:见代码中的测试用例
想达到的目的:之前想通过switch_to.window到第二个窗口,然后通过switch_to.alert确认,发现卡住。最终通过模拟键盘的方式确认掉最初的alert,让后续代码可以继续执行。

不是冲突,是重复了,相当于switch_to了2次

hi,Yourwhat:
请问这个问题你有更进一步的解决方案吗?遇到同类型问题,无法获取新弹出window中弹出的alert。

同问,我是在第二个窗口操作后,第一个窗口弹出alert,需要点击alert的确认后才能关闭第二个窗口,就算执行driver.close()也卡住,直到selenium报Timed out。

虽然现象有区别,但是感觉原理同楼主。

感觉第一个窗口的alert窗口冻结住了所有的窗口操作

time.sleep(1)
driver.close()
time.sleep(3)
windows = driver.window_handles
driver.switch_to.window(windows[-1])
time.sleep(3)
driver.switch_to.alert.dismiss()