Python and Selenium - Disable alert when leaving page

后端 未结 2 988
后悔当初
后悔当初 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: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.

提交回复
热议问题