使用Python和PhantomJS结合Selenium将文件下载到文件系统

21

我一直在尝试使用 PhantomJS/Selenium/python-selenium 将文件下载到文件系统中。我能够轻松地浏览 DOM 并点击、悬停等操作,但是下载文件却非常麻烦。我已经尝试过使用 Firefox 和 pyvirtualdisplay 的无头模式,但效果并不好,速度也非常慢。我知道 CasperJS 允许文件下载,但是否有人知道如何将 CasperJS 与 Python 集成或如何利用 PhantomJS 下载文件呢?非常感谢。

4个回答

19

尽管这个问题很老,但是通过PhantomJS下载文件仍然是一个问题。但我们可以使用PhantomJS获取下载链接并获取所有所需的cookie,例如csrf tokens等。然后我们可以使用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将其写入文件中,或者进行任何我们想要的操作。


12

PhantomJS目前不支持文件下载。相应的问题和解决方法如下:

据我所知,你至少有3种选择:

  • 切换到casperjs(并在此处离开python)
  • 尝试使用xvfb无头模式
  • 切换到普通的非无头浏览器

这里还有一些可能有帮助的链接:


5
似乎PhantomJS已经添加了文件下载功能(包括在您链接的线程中的相关评论)。然而,我不确定这是否以易于使用的方式在Selenium中公开。 - John Y

3

我的使用情况需要提交表单以检索文件。我可以使用驱动程序的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)

-1

那种方式不可行。您可以使用其他替代方案来下载文件,如wget或curl。

使用Firefox查找正确的请求,使用Selenium获取该值,最后使用out of the box来下载文件。

curlCall=" curl 'http://www_sitex_org/descarga.jsf' -H '...allCurlRequest....' > file.xml"
subprocess.call(curlCall, shell=True)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接