2016-11-02 96 views
0

我想刮一个网页,点击一个链接导致一个新的窗口弹出打开,立即下载CSV文件。我一直无法找出url的格式,因为它的javascript相当密集(并且通过onClick属性调用了一个函数,而另一个函数是href属性的一部分。我之前没有和Selenium一起工作过,所以我希望在开始之前确认我想要做的事情是可能的我曾经在某处读过通过新的弹出窗口下载文件并不一定是我可以用Selenium做的事情使用硒通过window.open下载文件

任何意见都将不胜感激A this is possible将会很有帮助,就像here's how you'd do it甚至可以详细描述一样。非常感谢!

很明显,我的困难主要来自于我无法弄清楚生成下载文件的URL。即使查看Google chrome网络调用,我也没有看到它的位置,并且可能需要几个小时才能跟踪此问题,因此我正在寻找一种解决方案,它依靠单击浏览器中的特定文本,而不是解开幕后操作繁琐。

回答

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) 
+0

谢谢基兰。这对你来说是非常慷慨的分享代码。我意识到自己的帖子并不清楚,我很难找出正在下载文件的URL,这是呈现我的困难的一部分。是否可以修改你的代码来选择我想要点击的文本来下载文件? – helloB

+0

@helloB您可以用'browser.find_element_by_xpath(xpath).click()'替换'browser.get',它仍然会将它下载到默认目录。 –

+0

真棒,要试试这个,谢谢你Kiran! – helloB