我一直在努力使用PhantomJS/Selenium/python-selenium将文件下载到文件系统。我能够轻松地在DOM中导航并单击、悬停等。然而,下载文件被证明是相当麻烦的。我用火狐和pyvirtualdisplay尝试了一种无头的方法,但效果也不好,而且速度慢得令人难以置信。我知道CasperJS允许下载文件。有人知道如何将CasperJS与Python集成,或者如何利用PhantomJS下载文件吗?非常感谢。
发布于 2016-02-27 12:56:08
尽管这个问题由来已久,但通过PhantomJS
下载文件仍然是一个问题。但是我们可以使用PhantomJS来获取下载链接,并获取所有需要的cookie,比如CSRF令牌等等。然后我们可以使用requests
下载它:
import requests
from selenium import webdriver
driver = webdriver.PhantomJS()
driver.get('page_with_download_link')
download_link = driver.find_element_by_id('download_link')
session = requests.Session()
cookies = driver.get_cookies()
for cookie in cookies:
session.cookies.set(cookie['name'], cookie['value'])
response = session.get(download_link)
现在,在response.content
中,实际的文件内容应该会出现。接下来,我们可以用open
编写它,或者做任何我们想做的事情。
发布于 2016-12-20 23:06:58
我的用例需要提交表单来检索文件。我能够使用驱动程序的execute_async_script()
函数来实现这一点。
js = '''
var callback = arguments[0];
var theForm = document.forms['theFormId'];
data = new FormData();
data.append('eventTarget', "''' + target + '''"); // this is the id of the file clicked
data.append('otherFormField', theForm.otherFormField.value);
var xhr = new XMLHttpRequest();
xhr.open('POST', theForm.action, true);
'''
for cookie in driver.get_cookies():
js += ' xhr.setRequestHeader("' + cookie['name'] + '", "' + cookie['value'] + '"); '
js += '''
xhr.onload = function () {
callback(this.responseText);
};
xhr.send(data);
'''
driver.set_script_timeout(30)
file = driver.execute_async_script(js)
发布于 2017-03-01 01:14:46
在这种情况下是不可能的。您可以使用其他替代方法来下载文件,如wget o curl。
使用firefox查找正确的请求,使用selenium获取该请求的值,最后使用out of to the box下载文件
curlCall=" curl 'http://www_sitex_org/descarga.jsf' -H '...allCurlRequest....' > file.xml"
subprocess.call(curlCall, shell=True)
https://stackoverflow.com/questions/25755713
复制相似问题