下面是我如何使用Firefox
webdriver下载文件。它本质上是创建一个浏览器配置文件,以便设置某些文件类型的默认下载位置。然后您可以验证文件是否存在于该位置。
import os
from selenium import webdriver
browser_profile = webdriver.FirefoxProfile()
# add the file_formats to download
file_formats = ','.join(["text/plain",
"application/pdf",
"application/x-pdf",
"application/force-download"])
preferences = {
"browser.download.folderList": 2,
"browser.download.manager.showWhenStarting": False,
"browser.download.dir": os.getcwd(), # will download to current directory
"browser.download.alertOnEXEOpen": False,
"browser.helperApps.neverAsk.saveToDisk": file_formats,
"browser.download.manager.focusWhenStarting": False,
"browser.helperApps.alwaysAsk.force": False,
"browser.download.manager.showAlertOnComplete": False,
"browser.download.manager.useWindow": False,
"services.sync.prefs.sync.browser.download.manager.showWhenStarting": False,
"pdfjs.disabled": True
}
for pref, val in preferences.items():
browser_profile.set_preference(pref, val)
browser_binary = webdriver.firefox.firefox_binary.FirefoxBinary()
browser = webdriver.Firefox(firefox_binary=browser_binary,
firefox_profile=browser_profile)
# set the file name that will be saved as when you download is complete
file_name = 'ABC.txt'
# goto the link to download the file from it will be automatically
# downloaded to the current directory
file_url = 'http://yourfiledownloadurl.com'
browser.get(file_url)
# verify if the expected file name exists in the current directory
path = os.path.join(os.getcwd(), file_name)
assert os.path.isfile(path)
谢谢基兰。这对你来说是非常慷慨的分享代码。我意识到自己的帖子并不清楚,我很难找出正在下载文件的URL,这是呈现我的困难的一部分。是否可以修改你的代码来选择我想要点击的文本来下载文件? – helloB
@helloB您可以用'browser.find_element_by_xpath(xpath).click()'替换'browser.get',它仍然会将它下载到默认目录。 –
真棒,要试试这个,谢谢你Kiran! – helloB