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

Python Selenium Webdriver-动态更改下载目录,python,selenium,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

为了在定义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)
我想下载一些文件,每个文件都到一个不同的(新创建的)目录。定义驱动程序后是否可以更改下载目录

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

试试这个变体。

我一直不知道怎么做,并且使用了一种变通方法。下面的解决方案不是动态更改webDriver下载目录,而是移动您下载的文件


我刚刚尝试了在webdriver运行期间更改下载文件夹的方法:

driver.command\u executor.\u commands['send\u command']=(
'POST','/session/$sessionId/chromium/send_命令')
下载路径='path/TO/MY/CURRENT/DESIRED'
参数={
'cmd':'Page.setDownloadBehavior',
'params':{'behavior':'allow','downloadPath':download_path}
}
执行(“发送命令”,参数)
或:

下载路径='path/TO/MY/CURRENT/DESIRED' 参数={'behavior':'allow','downloadPath':download_path} driver.execute_cdp_cmd('Page.setDownloadBehavior',params['params'])
它不会更改Chrome的默认下载位置设置,但会在后续下载中将文件保存到新的给定文件夹中(如果不存在将创建)。

尝试了此操作,但出现错误:AttributeError:“WebDriver”对象没有属性“set\u preference”可能重复
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