Ruby · save_images · watir

How do I save all images on a webpage?

Answer:

Code:

require ‘watir’

browser = Watir::IE.new
browser.visible=true
browser.goto(‘http://in.youtube.com/’)

idx = 0

# using the images collection, iterate through all of the images on a page
browser.images.each do |x|
idx += 1
# apparently the string accepted by the string method will not allow variable substitution
original_type= x.src[-4,4]

type=”.gif” if original_type == ‘.gif’
type=”.jpg” if original_type == ‘.jpg’
type=”.png” if original_type == ‘.png’
type=”.bmp” if original_type == ‘.bmp’
type=”jpeg” if original_type == ‘.jpeg’

location = ‘C:\TML\fileq-‘ + idx.to_s + type
x.save(location)
end

Advertisements

2 thoughts on “How do I save all images on a webpage?

  1. Hi Raveendran,
    I try to execute the watir scripts you have described with the title
    “How do I save all images on a webpage?”
    When i execute the script, i am getting error below. Am i making any mistake on this?
    >ruby youtubeImage.rb
    youtubeImage.rb:1: Invalid char `\221′ in expression
    youtubeImage.rb:1: Invalid char `\222′ in expression
    youtubeImage.rb:4: Invalid char `\222′ in expression
    youtubeImage.rb:4: syntax error, unexpected kIN
    browser.goto(’http://in.youtube.com/’)
    ^
    youtubeImage.rb:4: Invalid char `\222′ in expression
    youtubeImage.rb:4: syntax error, unexpected ‘)’
    youtubeImage.rb:7: syntax error, unexpected kDO_BLOCK, expecting $end
    browser.images.each do |x|
    ^
    >Exit code: 1

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s