もけへへ倶楽部 RSSフィード

2008-01-14

[] Google検索結果のスクレイピング

GoogleのサーチAPIの新規登録ってなんで廃止されちゃったんだろう…。AJAX版は使えるけど、サーバ側などで加工できないから不便。

しかたがないのでスクレイピング。Hpricot を使って:

#!/usr/local/bin/ruby -Ku

require 'rubygems'
require 'hpricot'
require 'open-uri'
require 'cgi'

API = "http://www.google.co.jp/search?num=10&lr=lang_ja&oe=utf-8&q="

word = ARGV.shift

url = "#{API}#{CGI.escape(word)}"
html = open(url).read
doc = Hpricot(html)

results = doc / "div.g"		# 検索結果は <div class=g> で囲まれてる
results.each_with_index do |div, idx|
	next if div.attributes['style']		# style が入ってる場合は、1段奥のものなので無視
	link = div.at "a"
	text = CGI.unescapeHTML(link.inner_html.gsub(%r!<b>([^<]*)</b>!) {$1})
	href = link[:href]
	puts "#{idx}\t#{text}\t#{href}"
end

「hpricot」の結果:

0	Greenbear Laboratory - Hpricot Showcase-Ja	http://mono.kmc.gr.jp/~yhara/w/?HpricotShowcaseJa
2	pylori*style wiki - HTMLパーサ Hpricot	http://tam.qmix.org/wiki/Hpricot.html
3	Hpricot - ξ;゜ー゜)ξ { 遅レス。	http://d.hatena.ne.jp/babie/20070529/1180404575
4	shunlp: hpricotいい。	http://shunlp.blogspot.com/2007/01/hpricot.html
5	rubyneko - hpricotのメソッド名に吹いた	http://ujihisa.nowa.jp/entry/314b0e249b
6	RubyのHpricotも便利さでは負けていないの巻 (CodeZine編集部ブログ)	http://blog.codezine.jp/editor/2007/10/rubyhpricot.php
7	fedora 8でrubyのhpricotを ≪ Dreamkeyboard’s Weblog	http://dreamkeyboard.wordpress.com/2007/12/23/14/
8	RubyのHpricotでニコニコ動画をスクレイピングしてみる(1) | METAMATE	http://eclipse.cspc.jp/perma/000229/
9	ひとりぶろぐ: [Zaurus]Ruby用ライブラリHpricotとWWW::Mechanizeの ...	http://moyashi.air-nifty.com/hitori/2007/10/zaurusrubyhpric_73e5.html
  • 結果のinner_htmlは検索語が「< b>〜< /b>」で囲まれている。のでgsubで置換して、unescapeHTML
  • あまり長いタイトルは「...」で省略されてしまう
トラックバック - http://d.hatena.ne.jp/mokehehe/20080114/hpricot