简体   繁体   中英

Download file in Headless Chrome, (python)

I tried everything to download a file in headless chrome but nothing works, I'm using Chrome version 86.0.4240.75 while ChromeDriver version: 86.0.4240.22, I've already tried any solution and none of them worked

download_dir = "/tmp/"
options.add_argument("--start--minimized")
options.add_experimental_option("prefs", {
  "download.default_directory": download_dir,
  "download.prompt_for_download": False,
})

browser.get(www.download.com)

browser.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')
params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': download_dir}}
command_result = browser.execute("send_command", params)

When I try to specify the download directory as well without headless mode it gives me a common download chrome error

My use case is a little different - I'm navigating to a page and submitting a form - but I am getting working downloads with this code:

    chrome_options = Options()
    chrome_options.add_argument("--headless")
    chrome_options.add_argument("--no-sandbox")
    chrome_options.add_argument("--disable-dev-shm-usage")

    chrome_prefs = {"download.default_directory": "/root/Downloads"}
    chrome_options.experimental_options["prefs"] = chrome_prefs
    chrome_prefs["profile.default_content_settings"] = {"images": 2}

    driver = webdriver.Chrome(options=chrome_options)
    driver.get('https://...redacted...')

    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, "//a[contains(text(),'ContractOp')]")))

    submit_button = driver.find_element_by_xpath("//button[contains(.,'Submit')]")
    submit_button.click()
    
    # wait for download to finish

  

Hope this is helpful for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM