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

标签 javascript python selenium screen-scraping

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

如有任何建议,我们将不胜感激。 这是可能的将会非常有帮助,就像这里是你如何做到这一点甚至详细描述一样。非常感谢!

需要明确的是,我的困难主要源于我无法弄清楚下载文件的 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)

关于javascript - 使用selenium通过window.open下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40383328/

相关文章:

javascript - 在年份的下拉列表中获取当前年份

javascript - Google Site Search 搜索按钮字形图标

python - 如何在 jupyterhub 页面中使用 python-selenium 查找现有的 HTML 元素?

java - 重复使用 Selenium 元素定位器的最佳方法是什么?

javascript - Angular 提供者错误 - 必须定义 $get 工厂方法

python - 在 pandas.Series 的大小为 k 的窗口中轻松找到每个第 n 个元素的平均值的方法? (不是滚动平均值)

python - WindowsError : [Error 2] The system cannot find the file specified, 无法在 Python 中解析

python - 如何将不同函数中的两个数据帧写入django中的一个excel文件中

java - 如何在不改变实际卡号的情况下屏蔽信用卡号以在selenium中发送 key ?

javascript - this.file.dataDirectory 在 ionic2 中显示为 null