title: How to save pictures from URL to disk
body: <p>I want to download pictures from a URL, like: <a href="http://trinity.e-stile.ru/" rel="nofollow">http://trinity.e-stile.ru/</a> and save images to a directory like "C:\pickaxe\pictures". It is important to use Nokogiri.</p>
  
  <p>I read similar questions on this site, but I didn't find how it works and I didn't understand the algorithm.</p>
  
  <ol>
  <li><p>I wrote the code where I parse the URL and put parts of the webpage source code with "img" tag into a links object:</p>
  
  <pre><code>require 'nokogiri'
  require 'open-uri'
  
  PAGE_URL="http://trinity.e-stile.ru/"
  page=Nokogiri::HTML(open(PAGE_URL))   #parsing into object
  links=page.css("img") #object with html code with img tag
  puts links.length # it is 24 images on this url
  puts
  links.each{|i| puts i } #it looks like: &lt;img border="0" alt="" src="/images/kroliku.jpg"&gt; 
  puts
  puts
  links.each{|link| puts link['src'] } #/images/kroliku.jpg 
  </code></pre>
  
  <p>What method is used to save pictures after grabbing the HTML code?</p></li>
  <li><p>How can I put the images into a directory on my disk?</p></li>
  </ol>
  
  <p>I changed the code, but it has an error:</p>
  
  <pre><code>/home/action/.parts/packages/ruby2.1/2.1.1/lib/ruby/2.1.0/net/http.rb:879:in `initialize': getaddrinfo: Name or service not known (SocketError)
  </code></pre>
  
  <p>This is the code now:</p>
  
  <pre><code>require 'nokogiri'
  require 'open-uri'
  require 'net/http'
  
  LOCATION = 'pics'
  if !File.exist? LOCATION         # create folder if it is not exist
      require 'fileutils'
      FileUtils.mkpath LOCATION
  end
  
  #PAGE_URL = "http://ruby.bastardsbook.com/files/hello-webpage.html"
  #PAGE_URL="http://trinity.e-stile.ru/"
  PAGE_URL="http://www.youtube.com/"
  page=Nokogiri::HTML(open(PAGE_URL))   
  links=page.css("img")
  
  links.each{|link| 
      Net::HTTP.start(PAGE_URL) do |http|
        localname = link.gsub /.*\//, '' # left the filename only
        resp = http.get link['src']
        open("#{LOCATION}/#{localname}", "wb") do |file|
          file.write resp.body
        end
      end
   }
  </code></pre>