Skip to content

Instantly share code, notes, and snippets.

@maraigue
Created June 9, 2011 03:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maraigue/1015967 to your computer and use it in GitHub Desktop.
Save maraigue/1015967 to your computer and use it in GitHub Desktop.
Google検索の「もしかして:C++++(中略)++++Template テクニック」の「++」はどこまで伸びるのかを検証するプログラム
#!/usr/bin/env ruby1.9
# -*- coding: utf-8 -*-
require 'open-uri'
require 'hpricot'
TRIAL_COUNTS = 10 # 何回繰り返すか
OUT_ENCODING = 'utf-8' # 結果を出力する際のエンコーディング
def read_google_search(path)
buf = nil
open("http://www.google.co.jp#{path}"){ |f| buf = f.read }
# google.co.jpはデフォルトだとSJISで結果を返すようなので
# 出力エンコーディングに合わせたものに変換している
buf.force_encoding('shift_jis')
buf.encode(OUT_ENCODING)
end
path = '/search?q=C%2B%2BTemplate+%E3%83%86%E3%82%AF%E3%83%8B%E3%83%83%E3%82%AF'
(1..TRIAL_COUNTS).each do |count|
buf = read_google_search(path)
html = Hpricot(buf)
# 「もしかして:」の結果は、「<a class="spell" ...>」の中に書かれている
html.search('a.spell').each do |doc|
# Googleのページ内では、href内のリンクが絶対パス
# (上記の「path」のような形式)で書かれている
path = doc['href']
puts "#{count}回目:"
puts "もしかして:#{doc.inner_html}"
break
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment