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.get'を' browser.find_element_by_xpath(xpath).click() 'に置き換えることができ、それでもデフォルトのディレクトリにダウンロードされます。 –
素晴らしい、これを試しに行く、ありがとう、キラン! – helloB