-
-
Save sai43/0bad6062b4ade398745c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'mechanize' | |
def google_search(query_text) | |
agent=Mechanize.new | |
goog = agent.get "http://www.google.com" | |
search = goog.form_with(:action => "/search") | |
search.field_with(:name => 'q').value = query_text | |
results = search.submit | |
return results | |
end | |
require 'tempfile' | |
def with_temp_string(s) | |
file = Tempfile.new("arbitrary_prefix") | |
file.write(s) | |
file.close | |
yield file.path | |
sleep 5 | |
file.unlink | |
end | |
require 'launchy' | |
ENV['BROWSER'] = 'google-chrome' | |
def browse_s(s) | |
with_temp_string(s) {|path| Launchy::Application::Browser.new.open(path)} | |
end | |
def browse_page(mechanize_page) | |
browse_s mechanize_page.body | |
end | |
def unwrap_link(l) | |
u = URI.parse(l) | |
p = CGI.parse(u.query) | |
return p['q'].first | |
end | |
def links(search_results) | |
return search_results.search("#ires ol .g .r a") | |
.map {|x| x['href']} | |
.keep_if {|x| URI.parse(x).path == "/url"} | |
.map {|x| unwrap_link x} | |
end | |
def im_feeling_lucky(search) | |
links = links(google_search(search)) | |
Launchy.open(links.first) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment