
# celerity (0.0.6)
# ruby 1.3.1 (ruby 1.8.6p287) (2009-06-15 2fd6c3d) (Java HotSpot(TM) 64-Bit Server VM 1.6.0_13) [x86_64-java]
# firefox 3.5.2

require 'rubygems'
require 'celerity'
require 'cgi'
require 'open-uri'
require 'pp'

DOWNLOAD_DIR = 'download'
START_PAGE = -1
END_PAGE= 2 # 999
QUERY = CGI.escape('micro bikini')

Dir::mkdir(DOWNLOAD_DIR) unless File.exist?(DOWNLOAD_DIR)

browser = Celerity::Browser.new

START_PAGE.upto(END_PAGE) do |page|
  browser.goto("http://image-search.yahoo.co.jp/detail?p=#{QUERY}&ei=&ib=#{page}")

  # target の イメージのリンクの src を探して、保存する
  browser.li(:class, "target").link(:target, "subwin").images.each do |x|
    begin
      location = "#{DOWNLOAD_DIR}/#{URI.decode(File.basename(x.src))}"
      x.save(location)
      puts "#{page} saved #{location}"
    rescue => ex
      pp "Error for #{x.src}"
      pp ex
    end
  end

  # [次] のイメージのリンクの存在を調べる
  break unless browser.li(:class, "next").link(:class, "next").exists?
end

browser.close
