如何防止硒(Chrome)覆盖现有下载的文件-Python
我正在自动化通过硒下载文件。 当我通过Selenium单击此下载按钮时,它将自动下载Excel文件。 不会打开任何提示,默认文件名是p3mlf.xls或p3mlf(xx).xls,xx =数字,取决于下载的最后一个文件。
我在正常模式下运行脚本时没有问题(不是无头)。 但是,在无头模式下,下载的文件名始终为p3mlf.xls并覆盖现有的p3mlf.xls文件,而无需添加新文件p3mlf(xx).xls。
我如何防止在无头模式下覆盖现有文件并正常下载。
这是我发现能够以无头模式下载的代码:
def download(self):
self.opt = webdriver.ChromeOptions()
self.opt.add_experimental_option('detach', True)
self.opt.add_argument('headless')
self.opt.add_argument('window-size=1920x1080')
self.opt.add_argument('disable-gpu')
self.opt.add_argument('--enable-javascript')
self.ser = Service('SupportingFiles\chromedriver.exe')
self.driver = webdriver.Chrome(options=self.opt, service=self.ser)
self.prefs = {
'profile.default_content_settings.popups': 0,
'download.default_directory': 'C:\\Drive_D\\Download', #this part actually not wowking
'download.prompt_for_download': False,
'download.directory_upgrade': True
}
self.opt.add_experimental_option("prefs", self.prefs)
self.driver.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')
params = {'cmd':'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': self.dlPath_box.get()}}
self.driver.execute('send_command', params)
I'm automating to download a file through selenium.
When I click this download button through selenium, it will automatically download the excel file.
No prompt will open, and the default file name is P3MLF.xls or P3MLF(xx).xls, xx = number depending on the last file downloaded.
I have no issue when running the script in normal mode (not headless).
But when in headless mode, downloaded file name is always P3MLF.xls and overwrites the existing P3MLF.xls file without adding a new file P3MLF(xx).xls.
How can I prevent to overwrite the existing file and download as normal in headless mode.
Here is my code I found to be able to download in headless mode:
def download(self):
self.opt = webdriver.ChromeOptions()
self.opt.add_experimental_option('detach', True)
self.opt.add_argument('headless')
self.opt.add_argument('window-size=1920x1080')
self.opt.add_argument('disable-gpu')
self.opt.add_argument('--enable-javascript')
self.ser = Service('SupportingFiles\chromedriver.exe')
self.driver = webdriver.Chrome(options=self.opt, service=self.ser)
self.prefs = {
'profile.default_content_settings.popups': 0,
'download.default_directory': 'C:\\Drive_D\\Download', #this part actually not wowking
'download.prompt_for_download': False,
'download.directory_upgrade': True
}
self.opt.add_experimental_option("prefs", self.prefs)
self.driver.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')
params = {'cmd':'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': self.dlPath_box.get()}}
self.driver.execute('send_command', params)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论