2016-09-23 4 views
0

로컬 사본을 다운로드해야하는 많은 zip 파일이 포함 된 url이 있습니다. 나는 지금까지 가지고있다 :Ruby를 사용하여 URL에서 파일 다운로드

require 'open-uri' 
require 'pry' 

def download_xml(url, dest) 
    open(url) do |u| 
    File.open(dest, 'wb') { |f| f.write(u.read) } 
    end 
end 

urls = ["http://feed.omgili.com/5Rh5AMTrc4Pv/mainstream/posts/"] 

urls.each { |url| download_xml(url, url.split('/').last) } 

그러나 나는 그 위치에있는 zip 파일에 액세스 할 수 없거나 반복 할 수 없다. 해당 URL의 끝에있는 각 zip 파일을 반복하여 배열에 액세스하고 메서드에서 다운로드 할 수 있습니까?

+0

정답으로 표시하는 것을 잊지 마시기 바랍니다. 고마워요! – mertyildiran

+0

나는 확실히 할 것이다! –

답변

1

그래서 처음 노코 기리 보석 설치, HTML을 구문 분석 노코 기리 보석을 사용하고 있습니다 :

noko.rb

require 'rubygems' 
require 'nokogiri' 
require 'open-uri' 

page = Nokogiri::HTML(open("http://feed.omgili.com/5Rh5AMTrc4Pv/mainstream/posts/")) # Open web address with Nokogiri 
puts page.class # => Nokogiri::HTML::Documents 

for file_link in page.css('a') # For each a HTML tag/link 
    if file_link.text[-4,4] != ".zip" # If it's not a zip file 
    next # Continue the loop 
    end 
    link = "http://feed.omgili.com/5Rh5AMTrc4Pv/mainstream/posts/" + file_link.text # Generate the zip file's link 
    puts link 
    open(file_link.text, 'wb') do |file| 
    file << open(link).read # Save the zip file to this directory 
    end 
    puts file_link.text + " has been downloaded." 
end 

I :

sudo apt-get install build-essential patch 
sudo apt-get install ruby-dev zlib1g-dev liblzma-dev 
sudo gem install nokogiri 

솔루션 문제에 대한 특정이 주석으로 코드를 설명했습니다.

결국에는 HTML 파일을 구문 분석하고 하나씩 다운로드 링크를 생성하고 끝에 다운로드 할 수 밖에 없습니다.

+0

굉장! 나는 오늘 저녁에 그것을 시도 할 것이다! 정말 고맙습니다! 나는 Nokogiri에 대해 읽었지만 많은 자원을 가지고 있지 않았다. 저는 C# MVC에서 일하며 저녁에는 집에 돌아갈 때까지 Local Ruby Users Group Slack 팀에서 아무도 사용할 수 없습니다. 하하하지만, 정말 고맙습니다 - 특히 의견! 다시 한 번 감사드립니다. 오늘 저녁에 다시보고하겠습니다. –

관련 문제