Selenium does not download with options passed to the Chrome driver

て烟熏妆下的殇ゞ 提交于 2019-12-24 10:49:53

问题


I want to download a file and I am able to do it with the code below. When I pass options to the driver, download does not start.

from selenium import webdriver
url = "http://wwwapps.tc.gc.ca/Saf-Sec-Sur/2/CCARCS-RIACC/DDZip.aspx"
driver.get(url)
driver.find_element_by_id("btnDownload").click()

I tried to pass following options, but download does not start:

from selenium import webdriver
url = "http://wwwapps.tc.gc.ca/Saf-Sec-Sur/2/CCARCS-RIACC/DDZip.aspx"
options = webdriver.ChromeOptions()
options.add_argument("download.default_directory=H:/")
options.add_argument('headless')
options.add_argument('window-size=1920x1080')
options.add_argument("disable-gpu")
with webdriver.Chrome(chrome_options=options) as driver:
    driver.get(url)
    driver.find_element_by_id("btnDownload").click()

I also tried:

from selenium import webdriver
url = "http://wwwapps.tc.gc.ca/Saf-Sec-Sur/2/CCARCS-RIACC/DDZip.aspx"
with webdriver.Chrome() as driver:
    prefs = {
    "download.default_directory": down_dir,
    "download.prompt_for_download": False,
    "download.directory_upgrade": True
    }

    options.add_experimental_option('prefs', prefs)
    driver.get(url)
    driver.find_element_by_id("btnDownload").click()

I would like to download the file with hidden browser window. Also, is there a way to close it just after successful download (using driver.quit())?

EDIT:

I removed duplicated driver instances - error that I made during copying pieces of code.


回答1:


You instantiate your webdriver twice, delete/comment out the other line:

with webdriver.Chrome(options=options) as driver:
    # driver = webdriver.Chrome(options=options)

Also not sure for Options class, I believe you should import it with:

from selenium.webdriver.chrome.options import Options

EDIT: yep, Chrome's not going to download in headless mode: SO answer.

So, the solution for you is:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

url = "http://wwwapps.tc.gc.ca/Saf-Sec-Sur/2/CCARCS-RIACC/DDZip.aspx"


def enable_download_in_headless_chrome(driver, download_dir):
    # add missing support for chrome "send_command"  to selenium webdriver
    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)

options = Options()
options.add_argument('--headless')
driver = webdriver.Chrome(options=options)
enable_download_in_headless_chrome(driver, "H:/")
driver.get(url)
driver.find_element_by_id("btnDownload").click()


来源:https://stackoverflow.com/questions/56778991/selenium-does-not-download-with-options-passed-to-the-chrome-driver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!