要在定义 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)
我想下载一些文件,每个文件到不同的(新创建的)目录。是否可以在定义驱动后更改下载目录?
最佳答案
我一直无法弄清楚如何做到这一点,并使用了变通方法。下面的解决方案只是移动您下载的文件,而不是即时更改 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
关于Python Selenium Webdriver - 动态更改下载目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22734399/