如何在webdriver运行时更改默认下载文件夹?
我正在下载几个不同的数据集,希望每个文件(或数据集)都能下载到指定的文件夹里。我已经学会了如何在这些页面上更改下载目录:
用Selenium Webdriver在Python中设置Chrome偏好设置
问题是,这些方法只让我在打开webdriver时更改下载目录。因为到达下载页面需要一些时间,所以这样做并不有效。我尝试过设置偏好,但我在使用selenium webdriver和Chrome的Python时,没能在StackOverflow或Python帮助文档中找到相关信息。即使在新驱动程序上切换窗口句柄也不行,因为它无法抓取另一个驱动程序已经打开的窗口。
下载网站的链接是定制的,所以也无法复制粘贴到新的驱动程序中。目前我一直在使用os模块来获取每个新文件的名称,但由于下载时间不一致,这种方法也不太可靠。
如果有人知道如何在webdriver运行时更改默认设置,那就太好了。谢谢!
3 个回答
-1
我使用了chromeOptions的实验性方法。
##set download directory
chromeOptions = webdriver.ChromeOptions()
prefs = {"download.default_directory": "your directory path"}
chromeOptions.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(executable_path='/usr/bin/chromedriver',
chrome_options=chromeOptions)
在这个例子中,我的chromedriver放在/usr/bin目录下。唯一的缺点是,你需要根据浏览器的更新来保持chromedriver的最新状态。所以当你更新浏览器的时候,也得更新chromedriver。
这个方法对我来说是有效的。
0
我在找一些东西,但没找到有用的资料。我觉得最好的办法是先声明一个临时的下载路径,然后再使用操作系统的库把你下载的文件移动到你想要的路径。
5
以前,我是通过先把文件下载到一个临时文件夹,然后再把它重命名并移动到合适的文件夹来解决这个问题的,具体做法大概是这样的:
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
## Click element to download file
inputElement=driver.find_element_by_xpath("{xpath here}").click()
move_to_download_folder(downloadPath, newFileName, fileExtension)