rubyのHpricotで属性名の大文字小文字を無視して検索する
rubyでhtml解析を行う際に便利なのがHpricot(エイチプリコット?)というhtmlパーサーです。
require 'rubygems' require 'Hpricot' require 'open-uri' open('http://www.yahoo.co.jp') do |f| doc = Hpricot(f) doc.search('img') do |img| puts img.attributes['src'] end end
こんな感じでYahoo!のトップページのimageタグの画像urlが抜き出せます。
しかし、困ったことにタグ名(imgなど)はhtmlソース中の大文字・小文字は
区別しないのですが、属性名(srcなど)は大文字と小文字を区別してしまいます。
つまりimg.attributes['src']では
<IMG SRC='hoge.jpg'>
が検出できない訳です。
こんなときはHpricot::Elemクラスのattributesを変更してやると幸せになれます。
require 'rubygems' require 'Hpricot' require 'open-uri' class Hpricot::Elem def attributes if raw_attributes raw_attributes.inject({}) do |hsh, (k, v)| #hsh[k] = Hpricot.uxs(v) hsh[k.downcase] = Hpricot.uxs(v) #hashのkeyを小文字に変換 hsh end end end end open('http://www.yahoo.co.jp') do |f| doc = Hpricot(f) doc.search('img') do |img| puts img.attributes['src'] end end
上記のattributesメソッドの中身はHpricotのバージョンによって多少違うみたいですので自分のPCにインストールされているソースを確認してみてください。