Python Selenium Webdriver - 动态更改下载目录
在定义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 个回答
-2
driver.set_preference("download.default_directory", "path/")
试试这个变种。
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
我一直搞不清楚怎么做这个,所以用了一个变通的方法。与其在运行时改变webDriver的下载目录,不如直接移动你下载的文件。
ExperimentsWithCode 在这里给出了答案。下面是他解决方案的一部分
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