繁体   English   中英

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

[英]Using selenium to download a file via window.open

我正在尝试抓取一个网页,在该网页上单击链接会导致弹出一个新窗口,该窗口会立即下载csv。 我无法确定url的格式,因为它是相当密集的javascript(而且一个函数是通过onClick属性调用的,而另一个函数是href属性的一部分。我以前没有使用Selenium,所以我我希望能够在开始之前确认我想做的事情。我读过某处文章说,通过新的弹出窗口下载文件不一定是我可以使用Selenium做的。

任何建议将不胜感激。 this is possible这将非常有帮助,因为here's how you'd do it甚至可以通过以下详细步骤来here's how you'd do it 非常感谢!

明确地说,我的困难主要源于我无法弄清楚如何下载文件的URL的事实。 即使看着Google 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM