内容へ移動
Cat Paw Software
ユーザ用ツール
ログイン
サイト用ツール
検索
ツール
文書の表示
以前のリビジョン
バックリンク
最近の変更
メディアマネージャー
サイトマップ
ログイン
>
最近の変更
メディアマネージャー
サイトマップ
トレース:
ruby:hpricot
この文書は読取専用です。文書のソースを閲覧することは可能ですが、変更はできません。もし変更したい場合は管理者に連絡してください。
====== Hpricot ====== [[http://github.com/whymirror/hpricot|Hpricot]]はRubyの軽量HTMLパーザ。要素へのアクセスはXPathで記述する。 作者のwhyさんは何処かに消えてしまったらしく、現在は別の人がメンテナンスしている。 ===== インストール ===== $ sudo gem install hpricot ===== 使い方 ===== 説明するよりサンプルコード、めざまし占いのページから星座と運勢を抜き出す例 <code ruby> require "rubygems" require "hpricot" require "open-uri" require "nkf" # SJISからUTF8変換 def filter(s) if s.nil? "" else NKF.nkf("-Sw", s) end end # openで取得したデータをそのまま渡せる、open-uriを使えばURLで指定したHTMLファイルを直接渡せる doc = Hpricot(open("http://www.fujitv.co.jp/meza/uranai/index.html")) # XPathで要素を抜きだし date = doc.search("//td[@class = 'day']")[1].inner_text # 抜き出した要素はEnumerableなので、mapメソッド等でまとめて処理できる。 items = doc.search("//table[@background ^= 'item/rank']").map { |table| item = {} item["star"] = table.search("img[@src ^= 'item/conste']").first["alt"] item["text"] = table.search("td[@class = 'text']").first.inner_text item["lucky"] = table.search("td[@class = 'lucky']").first.inner_text item } # 表示 puts filter date items.each { |item| puts filter item["star"] puts filter item["text"] puts filter item["lucky"] } </code>
ruby/hpricot.txt
· 最終更新:
2009/10/31 14:55
by
127.0.0.1
ページ用ツール
文書の表示
以前のリビジョン
バックリンク
文書の先頭へ