Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I open a web page and write it to a file in ruby?

Tags:

ruby

If I run a simple script using OpenURI, I can access a web page. The results get written to the terminal.

Normally I would use bash redirection to write the results to a file.

How do I use ruby to write the results of an OpenURI call to a file?

like image 300
bob Avatar asked Jun 12 '11 09:06

bob


People also ask

What is file handling in Ruby?

It is a way of processing a file such as creating a new file, reading content in a file, writing content to a file, appending content to a file, renaming the file and deleting the file. Common modes for File Handling. “r” : Read-only mode for a file. “r+” : Read-Write mode for a file.

What are the Ruby file open modes?

Ruby allows the following open modes: "r" Read-only, starts at beginning of file (default mode). "r+" Read-write, starts at beginning of file. "w" Write-only, truncates existing file to zero length or creates a new file for writing.

How do you download a file in Ruby?

Plain old Ruby The most popular way to download a file without any dependencies is to use the standard library open-uri . open-uri extends Kernel#open so that it can open URIs as if they were files. We can use this to download an image and then save it as a file.


1 Answers

require 'open-uri'

open("file_to_write.html", "wb") do |file|
  URI.open("http://www.example.com/") do |uri|
     file.write(uri.read)
  end
end

Note: In Ruby < 2.5 you must use open(url) instead of URI.open(url). See https://bugs.ruby-lang.org/issues/15893

like image 197
Michaël Witrant Avatar answered Oct 20 '22 00:10

Michaël Witrant