使用selenium通过window.open

时间:2016-11-02 15:07:19

标签: javascript python selenium screen-scraping

我试图抓取一个网页,点击一个链接会弹出一个新窗口,立即下载一个csv。我还没有能够找出网址的格式,因为它是相当密集的javascript(一个函数是通过onClick属性调用的,而另一个函数是{{1}的一部分。我之前没有和Selenium合作,所以我希望在开始之前确认我想要做的事情是可能的。我曾经读过某个地方,通过新的弹出窗口下载文件不一定是我可以用Selenium做的事情

任何建议都将不胜感激。 href会非常有用,就像this is possible一样,甚至可以详细描绘。非常感谢!

要说清楚,我的困难主要源于我无法弄清楚如何生成下载文件的URL。即使查看谷歌Chrome网络电话,我也没有看到它在哪里,我可能需要花费很多时间才能跟踪它,所以我正在寻找一种解决方案,它依赖于点击浏览器中的特定文本而不是解开幕后工作繁琐的机器。

1 个答案:

答案 0 :(得分:0)

以下是我使用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)