Disable all downloads with ChromeDriver and Selenium

后端 未结 2 2014
执笔经年
执笔经年 2021-01-26 10:04

When accessing some static files such as hudoig.gov/sites/default/files/documents/2016-FW-1007.pdf (random example) with Selenium using ChromeDriver, the file is automatically d

相关标签:
2条回答
  • 2021-01-26 10:09

    Preferences for ChromeDriver are an experimental options.

    You could set download preferences explicitly and have PDF documents opened directly in the Chrome browser.

    For example:

    from selenium import webdriver
    
    options = webdriver.ChromeOptions()
    
    prefs = {
        "download.open_pdf_in_system_reader": False,
        "download.prompt_for_download": True,
        "plugins.always_open_pdf_externally": False
    }
    options.add_experimental_option(
        "prefs", prefs
    )
    driver = webdriver.Chrome(
        options=options
    )
    driver.get(
    "https://www.hudoig.gov/sites/default/files/documents/2016-FW-1007.pdf"
    )
    driver.close()
    

    Or you could set the download location to write the document to a virtual device file as /dev/null effectively discarding it.

    For example:

    prefs = {
        "download.open_pdf_in_system_reader": False,
        "download.prompt_for_download": True,
        "download.default_directory": "/dev/null",
        "plugins.always_open_pdf_externally": False
    }
    options.add_experimental_option(
        "prefs", prefs
    )
    

    You could set download restrictions to block all downloads.

    prefs = {
        "download_restrictions": 3,
    }
    options.add_experimental_option(
        "prefs", prefs
    )
    
    0 讨论(0)
  • 2021-01-26 10:17

    Another approach that you could take would be disabling the browser's ability to download. Namely, configure the DownloadRestrictions policy, discussed here.

    0 讨论(0)
提交回复
热议问题