【问题标题】:Python Selenium Webdriver - Dynamically change download directoryPython Selenium Webdriver - 动态更改下载目录
【发布时间】:2014-03-29 17:32:47
【问题描述】:

要在定义 selenium webdriver 之前明确定义下载目录,我们使用以下代码:

chromeOptions = webdriver.ChromeOptions()
prefs = {"download.default_directory" : "C:/data/cline"}
chromeOptions.add_experimental_option("prefs",prefs)
chromePath = "path to chromedriver"

driver = selenium.webdriver.chrome.webdriver.WebDriver(executable_path=chromePath, port=0,    chrome_options=chromeOptions, service_args=None, desired_capabilities=None,   service_log_path=None)

我想下载多个文件,每个文件到不同的(新创建的)目录。定义驱动后是否可以更改下载目录?

【问题讨论】:

标签: python selenium


【解决方案1】:

我一直无法弄清楚如何做到这一点并使用了解决方法。下面的解决方案不是动态更改 webDriver 下载目录,而是移动您下载的文件。

ExperimentsWithCode Gave the Answer Here. Below is part of his solution

def move_to_download_folder(downloadPath, newFileName, fileExtension):
    got_file = False   
    ## Grab current file name.
    while got_file = False:
        try: 
            currentFile = glob.glob(DOWNLOAD_PATH+"*"+fileExtension)
            got_file = True

        except:
            print "File has not finished downloading"
            time.sleep(20)

    ## Create new file name
    fileDestination = downloadPath+newFileName+fileExtension

    os.rename(currentFile, fileDestination)

    return

【讨论】:

    【解决方案2】:

    我只是在 webdriver 运行期间尝试了这种方式来更改下载文件夹:

    driver.command_executor._commands['send_command'] = (
        'POST', '/session/$sessionId/chromium/send_command')
    download_path = 'PATH/TO/MY/CURRENT/DESIRED'
    params = {
        'cmd': 'Page.setDownloadBehavior',
        'params': { 'behavior': 'allow', 'downloadPath': download_path }
    }
    driver.execute("send_command", params)
    

    或:

    download_path = 'PATH/TO/MY/CURRENT/DESIRED'
    params = { 'behavior': 'allow', 'downloadPath': download_path }
    driver.execute_cdp_cmd('Page.setDownloadBehavior', params['params'])
    

    它不会更改 Chrome 的默认下载位置设置,但会在后续下载时将文件保存到新的给定文件夹(如果不存在则创建)。

    【讨论】:

      【解决方案3】:
      driver.set_preference("download.default_directory", "path/")
      

      试试这个变种。

      【讨论】:

      • 试过这个并得到这个错误:AttributeError: 'WebDriver' object has no attribute 'set_preference'
      猜你喜欢
      • 2013-08-04
      • 2015-06-28
      • 2022-06-12
      • 1970-01-01
      • 2022-10-19
      • 2018-06-21
      • 2018-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多