LoginSignup
4
2

More than 3 years have passed since last update.

Rubyを利用して、インターネット上のファイルをダウンロードし、ローカルに保存したい (注意点あり)

Last updated at Posted at 2020-09-17

課題

Rubyを利用して、インターネット上のファイルをダウンロードし、ローカルに保存したい場合はどのようにすればよいでしょうか?

解決策

まずはテキストファイルの例です。Wikipedia - HyperText Markup LanguageをHTMLファイルとしてダウンロードしたい場合は次のように書くと良いです。

require 'open-uri'

uri_str = 'https://ja.wikipedia.org/wiki/HyperText_Markup_Language'
URI.open(uri_str) do |res|
  IO.copy_stream(res, 'HyperText_Markup_Language.html')
end

画像のようなバイナリでも同じです。Wikipedia - Portable Network GraphicsにPNGファイルの例としてあげられている画像をダウンロードしてみましょう。

require 'open-uri'

uri_str = 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png'
URI.open(uri_str) do |res|
  IO.copy_stream(res, 'PNG_transparency_demonstration_1.png')
end

注意

open-uriライブラリはNet::HTTPNet::HTTPSNet::FTPなどのラッパーで、httpやhttpsのURLを一般的なファイルのように扱うことができます。このライブラリはKernel#openを再定義するため、以下のように書くこともできます。

require 'open-uri'

uri_str = 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png'
open(uri_str) do |res|
  IO.copy_stream(res, 'PNG_transparency_demonstration_1.png')
end

ただし、Ruby2.7からはopen-uriにより拡張されるKernel#openを使って、URIを開くのは非推奨になりました。上記のコードをRuby2.7で実行すると、以下のような警告が出ます。

warning: calling URI.open via Kernel#open is deprecated, call URI.open directly or use URI#open

警告が出るだけで動かなくなったわけではないのですが、URI#openOpenURI#open_uriを利用することをお勧めします。

環境情報

$ ruby -v
ruby 2.7.1p83 (2020-03-31 revision a0c7c23c9c) [x86_64-darwin18
4
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2