2014-09-24 50 views
0

我必須向發送文件的頁面www.example.com/xls_file發送請求。我有Nokogiri和機械化可用。我將如何下載該文件並將其保存在本地?Ruby/Nokogiri/Mechanize:如何下載XLS文件?

def file 
    grab_file if !File.exists?("sales_data.csv") 
    File.open("sales_data.csv") 
end 

def grab_file 
    # What do I do here? 
    # Nokogiri::HTML(open("http://www.example.com/xls_file")) 
end 
+1

退房這[SO回答](http://stackoverflow.com/questions/2263540/how-do-i-download-a-binary-file-over-http)。它有很多選項,包括使用'net/http'或'open-uri'來下載文件。 – orde 2014-09-24 15:22:31

回答

1
require 'open-uri' 

File.open('any_name_here.xls', 'wb') do |file| 
file << open('http://www.example.com/xls_file.xls').read 
end 

如果你想從以https開始得到文件的網站://那麼你可能要添加下面的事情,以避免紅寶石報告SSL錯誤:

require 'open-uri' 
require 'openssl' 

File.open('any_name_here.xls', 'wb') do |file| 
    file << open('https://www.example.com/xls_file.xls', ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE).read 
end