1
2

More than 5 years have passed since last update.

nokogiriスクレイピング練習 もうすこし他のケースも試す

Last updated at Posted at 2015-07-26

はじめに

nokogiriの使い方を勉強しながら、rubyの復習をするような話。

前提条件

rubyはもちろん、gemにnokogiriが存在すること
実行するソースファイルと処理対象ファイルが同じディレクトリに存在すること(コード参照。読み込むファイルを)

処理対象(仮にread.htmlとする) 前回と同じ

ここで記載されているソース
http://vsanna.sakura.ne.jp/wp/2015/01/scraping_start_up2/

コード perser1-1.rb(ツッコミどころ満載)


# ノコギリ読み込みます。
require 'nokogiri'

#呼び出し部分をメソッド化する
def iwant(doc,list)
    #欲しいものを拾って
    what_i_want = (doc).xpath(list)
    #単純表示
    puts what_i_want
end


#読み込みたいファイルを読み込んでインスタンス生成
f = File.open("read.html")
doc = Nokogiri::HTML(f);
f.close

#対象リスト指定し、メソッド呼び出し
list ="html/body/p"
comment = "pタグで囲われているものを抽出するケース。"

hash = {"list" => list , "comment" => comment }

print(hash)
puts "\n"
iwant(doc,list)

list= "/html/body/ul/li"
comment = "liタグで囲われているものを抽出するケース。"

hash = {"list" => list , "comment" => comment }

print(hash)
puts "\n"
iwant(doc,list)


list= "/html/body/ul/li[1]"
comment = "liタグで囲われている最初の一つを抽出するケース。"

hash = {"list" => list , "comment" => comment }

print(hash)
puts "\n"
iwant(doc,list)

実行コマンド


$ ruby parser1-1.rb

実行結果

Qiita上ではうまく表示できないので、
こちらを参照(gistにしました)

余談

メソッドと引数で与えてみた。
これも前振りです

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2