簡體   English   中英

結合使用Selenium和Python和PhantomJS將文件下載到文件系統

[英]Using Selenium with Python and PhantomJS to download file to filesystem

我一直在努力使用PhantomJS / Selenium / python-selenium將文件下載到文件系統。 我能夠輕松瀏覽DOM並單擊,懸停等。但是,下載文件被證明是相當麻煩的。 我已經嘗試過使用Firefox和pyvirtualdisplay的無腦方法,但是這種方法也不能很好地運行,而且速度令人難以置信。 我知道CasperJS允許下載文件。 有誰知道如何將CasperJS與Python集成或如何利用PhantomJS下載文件。 非常感激。

盡管這個問題已經很老了,但是通過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它來編寫它,也可以做我們想做的任何事情。

PhantomJS當前不支持文件下載。 解決方法的相關問題:

據我了解,您至少有3種選擇:

  • 切換到casperjs (您應該在這里保留python)
  • 嘗試在xvfb上無頭
  • 切換到普通的非無頭瀏覽器

這里還有一些可能也有幫助的鏈接:

我的用例需要提交表單才能檢索文件。 我能夠使用驅動程序的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)

用這種方式是不可能的。 您可以使用其他替代方法來下載文件,例如wget o curl。

使用firefox查找正確的請求,使用硒獲取該請求的值,最后使用開箱即用的格式下載文件

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM