Python Selenium Webdriver - 动态更改下载目录

时间:2014-03-29 17:32:48

标签: python selenium

要在定义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)

我想下载一些文件,每个文件到另一个(新创建的)目录。是否可以在定义驱动程序后更改下载目录?

3 个答案:

答案 0 :(得分:0)

我一直无法弄清楚如何做到这一点,并使用了一个解决方法。以下解决方案只是移动您下载的文件,而不是动态更改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

答案 1 :(得分:0)

我只是尝试在 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 的默认下载位置设置,但会在后续下载中将文件保存到新的给定文件夹(如果不存在则创建)。

答案 2 :(得分:-2)

driver.set_preference("download.default_directory", "path/")

尝试此变体。