1. 简介
在使用selenium操作浏览器下载文件时,在下载完文件后通常会弹出提示,询问用户是否保存,并且该弹窗属于浏览器本身,selenium无法对其进行捕获和操作,如下图: 原图 对于chrome内核的浏览器来说,可以通过设置其启动项,来对浏览器的默认下载目录、以及该弹窗进行控制,从而让浏览器直接将文件下载到默认目录,而不再弹出询问框。
2. edge浏览器设置实例
edge浏览器的设置实例如下:
class GetEdgeDriver:
__singleton = None
def __new__(cls, *args, **kwargs):
if cls.__singleton is None:
options = {
"browserName": "MicrosoftEdge",
"version": "",
"platform": "WINDOWS",
"ms:edgeOptions": {
"extensions": [], "args": ["--start-maximized"],
"prefs": {'download.prompt_for_download': False, 'download.default_directory': "C:\\Download", }
},
}
cls.__singleton = Edge(capabilities=options)
cls.__singleton.command_executor._commands["send_command"] = (
"POST", '/session/$sessionId/chromium/send_command')
params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': "C:\\Download"}}
cls.__singleton.execute("send_command", params)
return cls.__singleton
2. Chrome浏览器设置实例
class GetChromeDriver:
__singleton = None
def __new__(cls, *args, **kwargs):
if cls.__singleton is None:
options = ChromeOptions()
prefs = {'download.prompt_for_download': False, 'download.default_directory': "C:\\Download", }
options.add_experimental_option("prefs", prefs)
cls.__singleton = Chrome(options=options)
cls.__singleton.command_executor._commands["send_command"] = (
"POST", '/session/$sessionId/chromium/send_command')
params = {'cmd': 'Page.setDownloadBehavior',
'params': {'behavior': 'allow', 'downloadPath': "C:\\Download"}}
cls.__singleton.execute("send_command", params)
cls.__singleton.maximize_window()
return cls.__singleton
|