#author("2017-06-20T14:24:31+09:00","default:wikiwriter","wikiwriter") &tag(nokogiri); *目次 [#c53d93ad] #contents *関連ページ [#j13318ad] -[[Ruby]] -[[Rails]] *参考情報 [#vdf1f104] -[[Tutorials - Nokogiri 鋸:http://www.nokogiri.org/]] *HTMLの解析 [#jbbb2018] -xpathあるいはcssで要素を指定できる。 -xpathを指定。 #pre{{ html=<<__EOM__ <html> <head><title>デモサイト</title></head> <body> <h1>見出し</h1> <div class="container"> <div class="row">行1 </div> <div class="row">行2 </div> </div> </body> </html> __EOM__ doc = Nokogiri::HTML.parse(html, nil, 'utf-8') p doc.title nodesets = doc.xpath("//div[@class='row']") p nodesets.class p nodesets.text p nodesets.first.class p nodesets.first.text }} -実行結果。 #pre{{ $ ruby demo.rb "デモサイト" Nokogiri::XML::NodeSet "行1\n 行2\n " Nokogiri::XML::Element "行1\n " }} *トラブルシューティング [#vea569ad] **IMPORTANT! Nokogiri builds and uses a packaged version of libxslt.って何? [#k7f4746b] -nokogiriが自前パッケージ版のlibxml2を使っているらしい。[[nokogiriのインストールでハマった件 - ひろうぃんの雑記:http://heroween.hateblo.jp/entry/2014/05/25/164302]]によるとシステム版のlibxml2を使うようにもできるらしいけど、とりあえずそのままでも良さそう。 **Yosemite環境でインストールできない [#s1ccccff] -railsなどをbundle installするときnokogiriが一緒にインストールされるのだが、これが失敗する。 -失敗する場合、nokogiri単体でインストールして状況を確認 gem install nokogiri -v '1.6.5' -以下のエラーメッセージでコンパイル失敗 #pre{{ checking for xmlParseDoc() in -llibxml2... no ----- libxml2 is missing. Please locate mkmf.log to investigate how it is failing. ----- }} -mkmf.logを確認すると(findで探せる)、libxml2が存在しないのではなく(デフォルトでnokogiriに同梱されているのでありえない)iconv関連のエラーのようだ。 #pre{{ Undefined symbols for architecture x86_64: "_iconv", referenced from: _main in conftest-a4367a.o "_iconv_open", referenced from: _main in conftest-a4367a.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) checked program was: }} -homebrewを使ってlibiconvをむりくり認識させる解放はあるようだが、MacPortsの場合どうやればいいか不明。 -とりあえず、環境変数を使って、システムライブラリを使うように指示したらコンパイルできた(環境変数が定義されていればよく、値はなんでもいいみたい) export NOKOGIRI_USE_SYSTEM_LIBRARIES=1 -もしくはつぎのように実行 NOKOGIRI_USE_SYSTEM_LIBRARIES=1 bundle install --path vendor/bundle/ *** extconf.rb failed *** [#ka5ec7fa] Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options. }}