使用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
甚至在广泛的细节中勾画。谢谢!明确地说,我的困难主要源于我不知道下载文件的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)
相关文章:
- 如何在生成下载文件时显示加载动画
- 直接下载文件,而不是从window.open(url)
- Javascript运行php文件,然后下载文件
- 在单击href链接的同时下载文件
- 通过javascript下载文件时设置文件名
- HTML锚标记无法在android平台中下载文件
- 链接/按钮从子文件夹下载文件--浏览器只是浏览
- iPhone强制下载文件
- 正在下载文件,同时加载另一个页面
- 如何在node.js中只下载文件的前10 KB
- 如何使用XMLHttpRequest下载文件
- 使用angular js在前端下载文件
- 使用blob从ajax结果下载文件
- 通过Android Chrome浏览器下载文件
- 使用AJAX下载文件.来自SD卡
- 如何使用phonegap从android中的URL下载文件
- 使用ajax下载文件
- 无法使用Angular JS和spring MVC打开下载文件
- 无法使用API-node.js从Google Drive下载文件
- 点击jQuery按钮下载文件