0
1

More than 3 years have passed since last update.

ダウンロードしたHTMLに対してスクレイピングしてCSV出力

Posted at

ダウンロードしたHTMLファイルに対してスクレイピングをかけてCSV出力したいときにどうぞ

(例えば。。。ツイッターのフォロワー画面は無限スクロール機能があると思います。最深部までスクロールした状態のHTMLをchoromeの検証機能でダウンロードしたらCSV形式であなたのフォロワーリストが作れますよ)


ディレクトリ構造
scraping
┝ target_html
┃ ┗ target.html
┝ scraping.rb
┗ result.csv


対象HTMLの構造

target.html
(省略)
<tr>
  (省略)
  <div class="name">
    <a>
      <span>なまえー</span>
    </a>
  </div>
 (省略)
  <div class="id">
    <a>あいでぃー</a>
  </div>
 (省略)
</tr>
(以下複数の別のtr)

scraping.rb
require "nokogiri"
require "csv"

f = File.open('./scraping/target_html/target.html')
doc = Nokogiri::HTML(f)

infos = []
trs = doc.xpath('//tr')

trs.each do |tr|
  name = tr.css('div[@class="name"]').css('a').css('span').inner_text
  id = tr.css('div[@class="id"]').css('a').inner_text
  info = [name,id]
  infos << info
end

CSV.open('result.csv', 'w') do |csv|
  infos.each do |info|
    csv << info
  end
end

f.close()

結果

result.csv
なまえー,あいでぃー
なまえー1,あいでぃー1
なまえー2,あいでぃー2
 ︙

以上

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