Skip to content

Instantly share code, notes, and snippets.

@kei-s
Created October 27, 2010 11:36
Show Gist options
  • Save kei-s/648881 to your computer and use it in GitHub Desktop.
Save kei-s/648881 to your computer and use it in GitHub Desktop.
http://d.hatena.ne.jp/gyuque/20101015 を参考に jQuery 読み込みとかオレオレ拡張いれた mozrepl.rb
require 'net/telnet'
require 'rubygems'
require 'json'
# for ruby 1.9.2-p0
class Net::Telnet
def method_missing(m, *args, &block)
@sock.__send__(m, *args, &block)
end
end
class MozRepl
def self.start(second=5, prompt=/^repl> /, host="localhost", port=4242)
mozRepl = MozRepl.new(second,prompt,host,port)
mozRepl.wait
yield mozRepl
mozRepl.close
end
def initialize(second=5, prompt=/^repl> /, host="localhost", port=4242)
@second = second
@prompt = prompt
@telnet = Net::Telnet::new(
"Host" => host,
"Port" => port,
"Prompt" => @prompt
)
end
def wait
@telnet.waitfor(@prompt)
end
def close
@telnet.close
end
def inject(url, script, with_jquery = false)
@telnet.cmd("content.location.href = 'about:blank'")
@telnet.cmd("content.location.href = '#{url}'")
if wait_load
@telnet.cmd("repl.enter(content)")
if with_jquery
STDERR.puts("Inject jQuery")
@telnet.cmd(<<JQUERY)
var script = document.createElement('script');
script.type = 'text/javascript';
script.charset = 'UTF-8';
script.src = 'http://code.jquery.com/jquery-1.4.3.min.js';
document.body.appendChild(script);
JQUERY
sleep 2
end
@telnet.cmd("repl.print( (function(){\n#{script}\n})() )") {|c|
result = c.gsub(@prompt, "")
yield result
}
@telnet.cmd("repl.back()")
end
end
private
def wait_load
loaded = false
STDERR.puts("Wait for load...")
@second.times{|i|
curloc = nil
@telnet.cmd("content.location.href") do |c|
curloc = c.gsub(@prompt,"")
end
if curloc != "about:blank"
loaded = true
end
STDERR.print("\b#{@second-1-i}")
sleep 0.5
}
STDERR.puts("\bdone")
return loaded
end
end
script =<<SCRIPT
var result = $("ul.rg_ul:first img.rg_i").map(function(){
return this.src;
});
return JSON.stringify($.makeArray(result));
SCRIPT
links = nil
MozRepl.start do |mozRepl|
mozRepl.inject("http://www.google.co.jp/images?q=richard+d.+james+album",script,true) do |json|
puts json
unless json.empty?
links = JSON.parse(json)
end
end
end
puts links
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment