Python and Selenium - Disable alert when leaving page

后端 未结 2 961
后悔当初
后悔当初 2021-01-20 23:50

Using Python 3 and Chromedriver.

Suppose an automated python program is surfing the web, fetching stuff from different sources.

相关标签:
2条回答
  • 2021-01-21 00:23

    Disable the alert on before unload:

    def super_get(url):
        driver.get(url)
        driver.execute_script("window.onbeforeunload = function() {};")
    

    And now use super_get(whatever_url) insetad of the standard driver.get(whatever_url)

    Disable all alerts in page:

    def super_get(url):
        driver.get(url)
        driver.execute_script("window.alert = function() {};")
    

    Hope it helps somebody. Cheers.

    0 讨论(0)
  • 2021-01-21 00:39

    Goal Get all listeners by getEventListeners(window)['beforeunload'] and remove them all.

    Step1. Put DOMDebugger.getEventListeners to window['getEventListeners']

    VB.NET

    Dim myChromeDriver as ChromeDriver = getMyDriver()
    myChromeDriver.ExecuteChromeCommand("Runtime.evaluate", New Dictionary(Of String, Object)() From {
    {"expression", "window['getEventListeners'] = getEventListeners;"},
    {"includeCommandLineAPI", True}})
    

    We don't need the result value of this Command.

    includeCommandLineAPI=True is required or it will throw exception because getEventListeners is an CommandLineAPI that is undefined in script execution context

    Step2. Remove all listeners

    Dim jsCmd As String = "var eventlistener = window['getEventListeners'](window)['beforeunload'][0];" &
    "    window.removeEventListener('beforeunload', " &
    "    eventlistener.listener, " &
    "    eventlistener.useCapture); "
    myChromeDriver.ExecuteScript(jsCmd)
    

    Run this script until getEventListeners(window)['beforeunload'] is empty.

    This script will throw exception when all listeners removed, you can fix it.

    Finally

    oDriver.Navigate.GoToUrl("https://www.google.com")
    

    The "Are you sure.." alert should disappear.

    0 讨论(0)
提交回复
热议问题