python-2.7seleniumselenium-chromedriver

Is there a delete_all_cookies() for ALL domains in Selenium / Chrome?


I'm using Python to automate Chrome with Selenium and Chromedriver. I specify a user-data-dir so that the browser has a persistent cache. The problem then is that it also persists cookies and I'd like to delete them prior to each automation run. The only reliable way I have found to do this is to delete all the records from the SQLite3 database $USER_DATA_DIR/Default/Cookies.

There is a method in Selenium webdrivers called delete_all_cookies() but it only removes cookies for the domain of the current URL!

Is there a better method or perhaps a command I can send ChromeDriver that will clear all cookies? Alternatively, is there a setting I can configure which will cause Chrome to remove cookies when it exits and/or starts up?


Solution

  • Chrome supports DevTools Protocol commands like Network.clearBrowserCookies that you can call remotely.

    driver.execute(
        "executeCdpCommand", 
        {"cmd": 'Network.clearBrowserCookies', params: {}}
    )
    

    Conveniently, DevTools Protocol also supports clearing all browser data:

    driver.execute(
        "executeCdpCommand", 
        {
            "cmd": "Storage.clearDataForOrigin", 
            "params": {"origin": "*", "storageTypes": "all"}
        }
    )
    

    Outdated answer:

    Selenium does not have an interface for this because it's not part of any standard.

    However, you can add support for these commands by patching Selenium's supported commands like this:

    send_command = ('POST', '/session/$sessionId/chromium/send_command')
    driver.command_executor._commands['SEND_COMMAND'] = send_command
    

    Now you can call any DevTools Protocol command like

    driver.execute('SEND_COMMAND', dict(cmd='Network.clearBrowserCookies', params={}))
    

    This deletes all cookies for all domains.