Chrome 无头模式下载文件

环境版本

chrome 版本: 76
selenium 版本: 4.1.3

解决办法

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


if __name__ == '__main__':
    options = Options()
    options.add_argument("--disable-notifications")
    options.add_argument('--no-sandbox')
    options.add_argument('--verbose')
    options.add_experimental_option("prefs", {
        "download.default_directory": "C:\\tmp",
        "download.prompt_for_download": False,
        "download.directory_upgrade": True,
        "safebrowsing_for_trusted_sources_enabled": False,
        "safebrowsing.enabled": False
    })
    options.add_argument('--disable-gpu')
    options.add_argument('--disable-software-rasterizer')
    options.add_argument('--headless')
    driver_path = "C:\\Users\\tmp\\chromedriver.exe"
    driver = webdriver.Chrome(driver_path, chrome_options=options)
    enable_download_headless(driver, "C:/tmp")
    driver.get(url)

参考链接

你可能感兴趣的:(爬虫,python,chrome,前端)