关闭beforeonload
Chrome解决方案:--disable-popup-blocking
通过ChromeOptions()使用:
from selenium import webdriver options.add_argument("--disable-popup-blocking") driver=webdriver.Chrome(chrome_options=options, executable_path=/path/to/chromedriver')
Firefox解决方案:dom.disable_beforeunload
通过FirefoxProfile()使用:
from selenium import webdriver profile = webdriver.FirefoxProfile() profile.set_preference("dom.disable_beforeunload", True) driver = webdriver.Firefox(firefox_profile = profile)
跨浏览器解决方案:作为跨浏览器解决方案,您可以禁用此对话框,调用executeScript()
将window.onbeforeunload设置为,function() {};
然后可以使用以下解决方案:
driver.execute_script("window.onbeforeunload = function() {};")
基于JQuery的解决方案:
$I->executeJS( "window.onbeforeunload = null" );
补充:
<html><body> <script> window.onbeforeunload = function() { return 'You have unsaved changes!'; } </script> <form> <input type='text' name='test'> <button type='submit'> </form> </body></html>
driver.get("<url-to-sample-page>"); driver.close(); WebDriverWait wait = new WebDriverWait(driver, 2); wait.until(ExpectedConditions.alertIsPresent()); driver.switchTo().alert().accept();