chromedriver 无头警报 [英] chromedriver headless alerts
问题描述
我在使用 chromedriver 进行 selenium webdriver 测试时遇到了这个问题.虽然我在使用 Chrome 浏览器时可以成功运行测试,但我无法在无头模式下运行相同的测试.
I have this issue with selenium webdriver tests with chromedriver. Although I can run tests succesfully when using Chrome browser I can't run the same tests in headless mode.
我无法处理 Js 警报.实际上在截屏时似乎甚至不会弹出警报.
I cannot handle the Js alerts. Actually when taking a screenshot it seems that the alert won't even pop-up.
我尝试了几种解决方法:
I have tried several workarounds:
1) driver.window_handles
--> 似乎没有其他窗口存在
1) driver.window_handles
--> No other window seems to be present
2) driver.execute_script("window.confirm = function(){return true;}")
--> 该脚本没有任何改变
2) driver.execute_script("window.confirm = function(){return true;}")
--> Nothing changed with that script
3) element = WebDriverWait(driver, 20).until(EC.alert_is_present())
当然还有显式等待
3) element = WebDriverWait(driver, 20).until(EC.alert_is_present())
and of course an explicit wait
在浏览器模式下,我使用纯文本:
In browser mode I use a plain:
try:
print driver.switch_to.alert.text
driver.switch_to.alert.accept()
except NoAlertPresentException as e:
print("no alert")
还有其他人在无头模式下遇到此问题吗?
Anyone else having this issue with alerts in headless mode?
- chromedriver v.2.30.477691
- Chrome 版本 59.0.3071.115
推荐答案
到 Chrome 61 仍然存在这个问题,所以我花了一段时间寻找不同的解决方案.由于它的简单性,我最喜欢的是在显示警报之前注入 javascript,以便自动接受警报.
Still having this problem as of Chrome 61, so I spent a while looking for a different solution. My favorite because of it's simplicity is injecting javascript before the alert is shown in order to automatically accept the alert.
只需将以下代码行放在导致显示警报的行之前:
Just put the following line of code before the line that causes the alert to be shown:
driver.ExecuteJavaScript("window.confirm = function(){return true;}");
适用于 headless chrome 和 PhantomJS.
Works with both headless chrome and PhantomJS.
这篇关于chromedriver 无头警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!