Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

selenium webdriver - chromedriver headless alerts

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.

I cannot handle the Js alerts. Actually when taking a screenshot it seems that the alert won't even pop-up.

Alert screenshot

I have tried several workarounds:

1) driver.window_handles --> No other window seems to be present

2) driver.execute_script("window.confirm = function(){return true;}") --> Nothing changed with that script

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 Version 59.0.3071.115
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;}");

Works with both headless chrome and PhantomJS.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...