Selenium Webdriver in Python - files download directory change in Chrome preferences

前端 未结 6 1577
逝去的感伤
逝去的感伤 2020-11-27 05:09

I\'m using Selenium Webdriver (in Python) to automate the downloading of thousands of files. I want to set Chrome\'s download folder programmatically. After reading this, I

6条回答
  •  無奈伤痛
    2020-11-27 05:46

    I try all the anwsers in this question, but it doesn't work for my in Ubuntu 16.10. So I add the change with os.environ for the variable XDG_DOWNLOAD_DIR. Which doesn't work, but I think that it helps.

    That is:

    os.environ['XDG_DOWNLOAD_DIR'] = default_download_directory
    

    The really change that works perfectly for me is setup the download folder via the command xdg-user-dirs-update through a system call in execution time:

    os.system("xdg-user-dirs-update --set DOWNLOAD " + default_download_directory)
    

    So, all my code related to setup the download dir is the following:

    import os
    from selenium import webdriver
    
    default_download_directory = str(os.path.dirname(os.path.abspath(__file__))) + "/download"
    
    os.environ['XDG_DOWNLOAD_DIR'] = default_download_directory
    
    os.system("xdg-user-dirs-update --set DOWNLOAD " + default_download_directory)
    
    desired_caps = {
        'prefs': {
                'download': {
                    'default_directory': str(os.path.dirname(os.path.abspath(__file__))) + "/download", 
                    "directory_upgrade": "true", 
                    "extensions_to_open": ""
                    }
                  }
            }
    
    options = webdriver.ChromeOptions() 
    options.add_argument("download.default_directory=" + str(os.path.dirname(os.path.abspath(__file__))) + "/download")
    
    browser = webdriver.Chrome(chrome_options=options, desired_capabilities=desired_caps)
    

提交回复
热议问题