使用Ruby从URL下载文件

使用Ruby从URL下载文件,ruby,download,uri,net-http,Ruby,Download,Uri,Net Http,我有一个url,其中包含许多zip文件,我需要下载这些文件的本地副本。到目前为止,我已经: 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/

我有一个url,其中包含许多zip文件,我需要下载这些文件的本地副本。到目前为止,我已经:

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文件,以便可以在该数组中访问它们并通过该方法下载?

我已使用Nokogiri gem解析HTML,因此首先安装Nokogiri gem:

sudo apt-get install build-essential patch
sudo apt-get install ruby-dev zlib1g-dev liblzma-dev
sudo gem install nokogiri
针对您的问题的解决方案:

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
需要“rubygems”
需要“nokogiri”
需要“打开uri”
page=Nokogiri::HTML(打开http://feed.omgili.com/5Rh5AMTrc4Pv/mainstream/posts/)#使用Nokogiri打开网址
放置page.class#=>Nokogiri::HTML::Documents
对于page.css('a')中的文件链接,每个文件都有一个HTML标记/链接
如果文件链接.text[-4,4]!=“.zip”#如果不是zip文件
接下来,继续循环
结束
链接=”http://feed.omgili.com/5Rh5AMTrc4Pv/mainstream/posts/“+file_link.text#生成zip文件的链接
放置链接
打开(file_link.text,'wb')do|文件|

请别忘了把我的答案标记为它应得的正确答案。谢谢!我一定会的!令人惊叹的!今晚我就试试看!非常感谢你!我读过关于Nokogiri的文章,但没有太多的资源。我在C#MVC工作,晚上回到家时,我们当地的Ruby用户组Slack团队中没有人。哈哈,但是,我真的很感激它-尤其是评论!再次感谢,我今晚回来汇报。