hakeの日記

Windows環境でプログラミングの勉強をしています。

Hpricotでhtmlの解析

Rubyの勉強
簡単な部分の機能を使ってみる。難しい部分はまだ良くわかっていません(^^ゞ
とりあえず以前勉強したREXMLでXMLの解析を行った雰囲気で簡単にhtmlの解析ができるっぽいです。


参考サイト

ザウルスのw3mのブックマークファイルbookmark.htmlを解析

以下の様なhtmlファイルです。

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=euc-jp">

<TITLE>Bookmarks</TITLE>
</head>
<body>
<h2>Search Box</h2>
<ul>
<li><a href="bookmark_utf8.html" target=new>Google & Wikipedia</a>
<li><a href="bookmark_sjis.html">Amazon</a>
<li><a href="bookmark_euc.html">はてな</a>
<!--End of section (do not delete this comment)-->
</ul>
<h2>Manual</h2>
<ul>
中略
<!--End of section (do not delete this comment)-->
</ul></body>
</html>

rubyスクリプト

#!/usr/bin/env ruby
require "rubygems"
require "hpricot"
#require "pp"
require "kconv"

doc = open("bookmark.html") { |f| Hpricot(f) }
title = (doc/:html/:head/:title)
#title = (doc/:title)
puts title.text.tosjis         #=> Bookmarks、<title>この部分</title>

uls = (doc/:html/:body/:ul)
p uls.class                    #=> Hpricot::Elements
puts "-----"


ul = doc.at("ul")              #=> 最初の<ul>…</ul>
#ul = uls[1]                   #=> 二番目の<ul>…</ul>
p ul.class                     #=> Hpricot::Elem

(ul/:li/:a).each do |a|        #=> aタグを検索
  puts a.name                  #=> a(タグ名)
  puts a.parent.name           #=> li(親要素のタグ名)
  puts a.inner_text.tosjis     #=> <a …>この部分</a>
# puts a.inner_html
  puts a.attributes['href']    #=> href=…の値
  p a.attributes['target']     #=> new、無ければnil
  puts "-----"
end

l = ul.at("li")                #=> 最初のli
p l.containers
     #=> [{elem <a href="bookmark_utf8.html" target="new"> "Google & Wikipedia" </a>}]
l = l.next_sibling             #=> 次の要素
p l.containers
     #=> [{elem <a href="bookmark_sjis.html"> "Amazon" </a>}]
p l.class  #=> Hpricot::Elem