使用Selenium和python将文件下载到指定位置 [英] Downloading file to specified location with Selenium and python

查看:74
本文介绍了使用Selenium和python将文件下载到指定位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,到目前为止,我已经将我的程序转到了我想从中下载链接并选择它的网站,然后会出现 Firefox 对话框,但我不知道该怎么做.我想将此文件保存到我桌面上的一个文件夹中.我正在使用它进行夜间构建,所以我需要它来工作.请帮忙.

Ok so far i have my programing going to the website i want to download link from and selecting it, then the firefox dialogue box shows up and i don't know what to do. i want to save this file to a folder on my desktop. I am using this for a nightly build so i need this to work. Please help.

这是我从网站上获取下载链接的代码:

Here is my code that grabs the download link from the website:

driver = web driver.Firefox()
driver.implicitly_wait(5)
driver.get("Name of web site I'm grabbing from")
driver.find_element_by_xpath("//a[contains(text(), 'DEV.tgz')]".click()

推荐答案

你需要让 Firefox 自动保存这个特定的文件类型.

You need to make Firefox save this particular file type automatically.

这可以通过设置 browser.helperApps.neverAsk.saveToDisk 首选项来实现:

This can be achieved by setting browser.helperApps.neverAsk.saveToDisk preference:

from selenium import webdriver

profile = webdriver.FirefoxProfile()
profile.set_preference("browser.download.folderList", 2)
profile.set_preference("browser.download.manager.showWhenStarting", False)
profile.set_preference("browser.download.dir", 'PATH TO DESKTOP')
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/x-gzip")

driver = webdriver.Firefox(firefox_profile=profile)
driver.get("Name of web site I'm grabbing from")
driver.find_element_by_xpath("//a[contains(text(), 'DEV.tgz')]").click()

更多解释:

  • browser.download.folderList 告诉它不要使用默认的 Downloads 目录
  • browser.download.manager.showWhenStarting 轮流显示下载进度
  • browser.download.dir 设置下载目录
  • browser.helperApps.neverAsk.saveToDisk 告诉 Firefox 自动下载所选 mime-types
  • 的文件
  • browser.download.folderList tells it not to use default Downloads directory
  • browser.download.manager.showWhenStarting turns of showing download progress
  • browser.download.dir sets the directory for downloads
  • browser.helperApps.neverAsk.saveToDisk tells Firefox to automatically download the files of the selected mime-types

您可以在浏览器中的 about:config 中查看所有这些首选项.这里还有一个非常详细的文档页面:About:config条目.

You can view all these preferences at about:config in the browser. There is also a very detailed documentation page available here: About:config entries.

此外,我不会使用 xpath 方法,而是使用 find_element_by_partial_link_text():

Besides, instead of using xpath approach, I would use find_element_by_partial_link_text():

driver.find_element_by_partial_link_text("DEV.tgz").click()

另见:

这篇关于使用Selenium和python将文件下载到指定位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆