Skip to main content
 首页 » 编程设计

python之在python中通过Selenium Webdriver下载文件

2024年08月20日47arxive

我正在编写一个程序,通过 python 中的 selenium webdriver 自动进行 Web 交互。当我通过脚本点击“下载”按钮时,我卡在了最后一步,屏幕上弹出一个窗口,默认选项“打开方式”被选中。我希望我的程序首先单击“保存文件”选项,然后单击“确定”。我使用以下代码来设置 Firefox 配置文件

profile = webdriver.FirefoxProfile() 
profile.set_preference('browser.download.folderList', 2) 
profile.set_preference('browser.download.manager.showWhenStarting', False) 
profile.set_preference('browser.download.dir', os.getcwd()) 
profile.set_preference('browser.helperApps.neverAsk.saveToDisk',"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") 

我的一个观察是当弹窗时是这样的

选项“从现在开始自动为这样的文件执行此操作”是可点击的(通过复选框)然后上面的代码片段工作完美,但是当相同的选项不可点击时(如下图所示)然后上面设置配置文件的代码失败。 在这种情况下有人可以帮助我吗?

请您参考如下方法:

当您使用新的 FirefoxProfile 时,请使用 set_preference 方法以这种方式配置配置文件,因此请单击 Save 和 Ok 并且在下载过程中不会中断。您可以按如下方式设置配置:

profile = webdriver.FirefoxProfile() 
profile.set_preference("browser.download.dir",os.getcwd()); 
profile.set_preference("browser.download.folderList",2); 
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/csv,application/excel,application/vnd.msexcel,application/vnd.ms-excel,text/anytext,text/comma-separated-values,text/csv,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/octet-stream"); 
profile.set_preference("browser.download.manager.showWhenStarting",False); 
profile.set_preference("browser.helperApps.neverAsk.openFile","application/csv,application/excel,application/vnd.msexcel,application/vnd.ms-excel,text/anytext,text/comma-separated-values,text/csv,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/octet-stream"); 
profile.set_preference("browser.helperApps.alwaysAsk.force", False); 
profile.set_preference("browser.download.manager.useWindow", False); 
profile.set_preference("browser.download.manager.focusWhenStarting", False); 
profile.set_preference("browser.download.manager.alertOnEXEOpen", False); 
profile.set_preference("browser.download.manager.showAlertOnComplete", False); 
profile.set_preference("browser.download.manager.closeWhenDone", True); 
profile.set_preference("pdfjs.disabled", True);