LoginSignup
1
3

More than 3 years have passed since last update.

【Ruby】Nokogiriでhtmlのデータをcsvファイルに出力

Last updated at Posted at 2019-11-13

概要

アウトプット用に、学習した内容を紹介していきます。
本日はNokogiriというライブラリを用いて、簡単なhtmlからデータをCSVに出力してみようと思います。

環境

Mac OS Mojave 10.14.6
Ruby 2.5.3
エディタ VSCode
Nokogiri 1.10.5

htmlで取得したデータをcsvに

以下のhtmlから、rowクラスのtitleとdescriptionを取得してcsvファイルに出力します。

training.html
<html>

<head>
  <meta charset="utf-8" />
</head>
<div class="row">
  <div class="title">タイトル1</div>
</div>
<div class="row">
  <div class="title"></div>
  <div class="description">解説2</div>
</div>
<div class="row">
  <div class="title">タイト",ル3</div>
  <div class="description">解説3</div>
</div>

</html>

これをcsvファイルに出力するコードが以下。

html_to_csv.rb
require 'nokogiri'
require 'CSV'

html = File.open('./training.html','r')

doc = Nokogiri.parse(html)

# div class="row"の取得
doc_row = doc.css('div.row')

doc_csv = []
# doc_csvにtitleとdescriptionを格納
doc_row.each do |row|
  doc_csv << [
    row.css('div.title').text,
    row.css('div.description').text
  ]
end

# Fileに出力
File.open('training.csv', 'w') do |file|
  # bomを付加
  file.print("\uFEFF")

  doc_csv.each do |row|
    file.puts(row.to_csv)
  end
end

doc = Nokogiri.parse(html)で開いたhtmlファイルをNokogiriで解析し、docに格納します。
rowクラスごとにtitle、descriptionを取得したいので、まずdoc_row = doc.css('div.row')でrow以下の階層を取得します。
その下のループでは、doc_csvにtitleとdescriptionの配列を一つずつ格納します。
最後にFILEに出力以下で、csvファイルへ出力します。
bomを付けることで、エクセルで開いても文字化けせずに表示してくれます。

CSV.generate(bom)などでもbomを付けることができますが、Rubyの2.5系でCSV.generateにバグがあるようです。この場合はRubyのバージョンを変更して用いる必要があります。

training.csv
タイトル1,""
"",解説2
"タイト"",ル3",解説3

titleとdescriptionが取得できました。またtitleやdescriptionが存在していない場合も空白として出力されています。

1
3
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
3