最近在使用selenium进行自动文件下载时,忽然出现了一个报错:python
下载进行不下去了。web
通过各类谷歌、百度,均告诉我在要增长params,关闭浏览器安全选项,配置以下:chrome
chromeOptions = webdriver.ChromeOptions() prefs = {"profile.default_content_settings.popups": 0, "download.default_directory": path, "download.prompt_for_download": False, # "download.directory_upgrade": 'true', "safebrowsing.enabled": True} chromeOptions.add_experimental_option("prefs", prefs)
事实证实,可能之前的版本是可行的,如今的真心不行。windows
上面配置重点是"safebrowsing.enabled": True
。在MacOS的环境下,哪怕不配也是没有问题的,Windows就不行了。浏览器
最后在谷歌上找到一篇相关文章,大意是说这个是无解的,多是windows系统安全的问题,安全
对于这个解释我仍是比较承认的,因此在mac上就不会提示。this
Let’s start frankly: you can’t disable this feature. You can merely tweak the download settings in order to avoid it.
那么问题来了,既然这样,有什么曲线救国的办法呢?code
当chromedriver弹出这个提示的时候,其实文件已经下载完成,以下图:blog
咱们只须要将文件名修改成正确的名字和后缀便可(好比test.txt),直接无视警告提醒。思路以下:
根据上面思路,实现的关键代码以下:
def sort_file(): global path dir_lists = os.listdir(path) dir_lists.sort(key=lambda fn: os.path.getmtime(os.path.join(path, fn))) return dir_lists[-1] def changeName(path, oldname, newname): old_path = os.path.join(path, oldname) new_path = os.path.join(path, newname + '.txt') if os.path.exists(old_path): if os.path.exists(new_path): os.remove(new_path) os.rename(old_path, new_path) print ('rename done!' + newname) else: print ('no file found!') def download(): ... temp_filename = sort_file() if u'未确认' in temp_filename: temp_filesize_old = os.path.getsize(os.path.join(path, temp_filename)) while True: time.sleep(1) temp_filesize_new = os.path.getsize(os.path.join(path, temp_filename)) if temp_filesize_old == temp_filesize_new: changeName(path, temp_filename, ip) return else: temp_filesize_old = temp_filesize_new else: print(u'下载失败')
须要注意的是,在文件重命名的时候,先检查下文件是否已经存在,先删除,在建立。
以上。
若是有更好的思路,欢迎分享。