user7496277
user7496277

Reputation:

How to fix chrome headless not downloading files?

I have set up webdriver with multiple configurations and it still fails to download files only in headless mode.

I've tried adding POST commands

chrome_options = webdriver.ChromeOptions()
prefs = {
    "download.default_directory": path,
    # "directory_upgrade": True,
    # "safebrowsing.enabled": False,
    "safebrowsing.disable_download_protection": True}
chrome_options.add_experimental_option("prefs", prefs)
if headless==True:
    chrome_options.add_argument('--headless')
# chrome_options.add_argument('log-level=2')
# chrome_options.add_argument('--disable-extensions')
# chrome_options.add_argument('--disable-gpu')
# chrome_options.add_argument('--no-sandbox')
local="/home/rittle/Workspace/portal_dl/chromedriver"
EC2="/home/ubuntu/portal_dl/chromedriver"
browser = webdriver.Chrome(executable_path=local,
    chrome_options=chrome_options,
)
browser.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')
params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': path}}
command_result = browser.execute("send_command", params)

I expect there to be a .crdownload file once a button on the page is clicked but my /tmp/ directory is empty, this code works fine without headless

Upvotes: 1

Views: 4614

Answers (2)

Sujan Maharjan
Sujan Maharjan

Reputation: 11

Override method create_webdriver of BrowserManagmentKeywords(under: SeleniumLibrary/keywords/browsermanagement.py) with execute command to enable download in headless chrome.


from SeleniumLibrary.base import keyword
from SeleniumLibrary.keywords import BrowserManagementKeywords

from selenium import webdriver

class CustomKeywords():

    def __init__(self):
        self.logger('Initializing Custom Keywords')

    @keyword
    def create_webdriver(self, driver_name, alias=None, kwargs={},
                     **init_kwargs):
        if not isinstance(kwargs, dict):
            raise RuntimeError("kwargs must be a dictionary.")
        for arg_name in kwargs:
            if arg_name in init_kwargs:
                raise RuntimeError("Got multiple values for argument    '%s'." % arg_name)
            init_kwargs[arg_name] = kwargs[arg_name]
        driver_name = driver_name.strip()
        try:
            creation_func = getattr(webdriver, driver_name)
        except AttributeError:
            raise RuntimeError("'%s' is not a valid WebDriver name." % driver_name)
        driver = creation_func(**init_kwargs)

        options = init_kwargs['chrome_options']
        args = options.to_capabilities()[options.KEY]['args']
        is_headless = '--headless' in args or 'headless' in args

        if is_headless:
            prefs = options.to_capabilities()[options.KEY]['prefs']
            download_dir = prefs['download.default_directory']
            self.enable_download_in_headless_chrome(driver, download_dir)

        driver = BrowserManagementKeywords(self)._wrap_event_firing_webdriver(driver)
        return BrowserManagementKeywords(self).ctx.register_driver(driver, alias)

    @keyword
    def enable_download_in_headless_chrome(self, driver, download_dir):

        #commands to enable download feature in headless chrome browser

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

        params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': download_dir}}
        driver.execute("send_command", params)

Upvotes: 1

Moshe Slavin
Moshe Slavin

Reputation: 5204

First, see this bug thread.

As of 4 days ago... what you need is to add the size of the headless...

if headless==True:
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--window-size=1920,1080')

As per the error:

unknown error: DevToolsActivePort file doesn't exist

You can add --disable-dev-shm-usage as an argument:

 chrome_options.add_argument('--disable-dev-shm-usage')

See @DebanjanB answer.

Hope this helps you!

Upvotes: 2

Related Questions