Downloading file through Selenium Webdriver in python

不羁岁月 提交于 2020-06-22 12:56:47

问题


I am writing a program to automate web interaction through selenium webdriver in python. I got stuck in last step when I click on the "download" button through script, a window pop-up occours on the screen,with default option "Open with" selected. I want my program to first click on the option "save file" and then click on "OK". I have used following piece of code to set up Firefox profile

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")

One of my observation is that when the window popup is like this

with option "Do this automatically for files like this from now on" is clickable (via checkbox) then the above piece of code works perfect, but when the same option is not clickable (as shown in the image below) then above code for setting profile fails. Can anyone help me in this situation?


回答1:


While you work with a new FirefoxProfile, use the set_preference method to configure the profile in such a way so clicks on Save and Ok and it doesn't gets interrupted in the downloading process. You can set the configuration as follows:

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);


来源:https://stackoverflow.com/questions/44342352/downloading-file-through-selenium-webdriver-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!