使用selenium通过window.open下载文件

Using selenium to download a file via window.open

本文关键字:下载 文件 open window selenium 通过 使用      更新时间:2023-09-26

我试图刮一个网页,点击一个链接,结果在一个新的窗口弹出,立即下载csv。我还没能弄清楚url的格式,因为它是相当密集的javascript(一个函数是通过onClick属性调用的,而另一个被称为href属性的一部分)。我以前没有使用过Selenium,所以我希望在开始之前确认我想做的事情是可能的。我曾在某处读到,通过新的弹出窗口下载文件不一定是我可以用Selenium做的事情。

如有任何建议,我将不胜感激。this is possible将非常有帮助,here's how you'd do it甚至在广泛的细节中勾画。谢谢!

明确地说,我的困难主要源于我不知道下载文件的URL是如何生成的。即使看一下谷歌chrome网络呼叫,我也没有看到它在哪里,这可能需要我花很多小时来追踪它,所以我正在寻找一个解决方案,依赖于点击浏览器中的特定文本,而不是在幕后解开繁琐的机器。

这是我如何使用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)