Save image with Mechanize and Nokogiri?

I use Mechanize and Nokogiri to collect some data. I need to save an image that is randomly generated on every request.

In turn, I have to upload all the photos, but the only thing I really need is an image located within the div#specific .

Also, is it possible to generate Base64 data from it without saving it, or reloading its source?

 require 'rubygems' require 'mechanize' require 'nokogiri' a = Mechanize.new { |agent| agent.keep_alive = true agent.max_history = 0 } urls = Array.new() urls.push('http://www.domain.com'); urls.each {|url| page = a.get(url) doc = Nokogiri::HTML(page.body) if doc.at_css('#specific') page.images.each do |img| img.fetch.save('picture.png') end end } 
+6
source share
1 answer

To get images from a specific location:

 agent = Mechanize.new page = agent.get('http://www.domain.com') images = page.search("#specific img") 

To save the image:

 agent.get(images.first.attributes["src"]).save "path/to/folder/image_name.jpg" 

To get an image without saving:

 encoded_image = Base64.encode64 agent.get(images.first.attributes["src"]).body_io.string 

I ran this to make sure that the encoded image can be decoded back:

 File.open("images/image_name.jpg", "wb") {|f| f.write(Base64.decode64(encoded_image))} 
+25
source

All Articles