【发布时间】:2017-05-07 23:27:38
【问题描述】:
我有一个 Python Selenium 脚本: A)在主窗口上做东西, B) 启动第二个窗口 C) 切换到第二个窗口 D) 在第二个窗口做事 E) 关闭第二个窗口 F) 切换回第一个窗口,继续做事。
但是,在步骤 F) 中,当我尝试切换回第一个窗口时,Chrome 会弹出“您要离开此站点吗?您所做的更改可能不会保存”弹出窗口。
mainWindow = driver.current_window_handle # remember which window handle is "main"
xpathlink = "//a[.='Click to select']"
driver.find_element_by_xpath(xpathlink).click() # here is step B
print(driver.window_handles) # this confirms yes, there are 2 window handles now
driver.switch_to_window(driver.window_handles[1]) # step C, switch to the newer window handle
#snip # step D - this executes as expected
rowButtonPath = 'xpath_to_button_that_closes_second_window'
driver.find_element_by_xpath(rowButtonPath).click() # step E - closes 2nd window
print(driver.window_handles) # this confirms there's just one window handle again -- the same as the one I started with
driver.switch_to_window(mainWindow) # step F - try to switch back to first one
如果我省略步骤 F 行,脚本会奇怪地挂起,好像驱动程序不知何故刚刚停止(我希望它继续前进,点击 driver.do_stuff() 的下一个实例,并给出错误,但它没有甚至不这样做。)
Chrome 弹出窗口不是通常意义上的 Selenium 警报。否则我只能switch_to_alert().accept()。
根据经验,解决方法似乎是: * 以不触发 Chrome 行为的方式返回第一个窗口 * 通过在启动 webdriver 实例时使用 Chrome 的选项来抑制此 Chrome 功能
...但我不知道该怎么做。
【问题讨论】:
-
一个想法,您可以将弹出页面设置为新的浏览器窗口,然后切换到它,做一些事情,关闭它,然后再次切换到上一个(比如这里stackoverflow.com/a/42205370/2397101)跨度>
-
但是无论如何,它应该被识别为警报,具有自己的 html 结构,换句话说,如果 accept() 不起作用,请参阅 xpath 以单击 Ok
标签: python google-chrome selenium