概要
nokogiriでスクレイピングした情報をCSVファイルに書き出しています。
アプリケーションフォルダ直下にcsvが保存されます。
(勉強がてら遊んでいたコードを備忘に残しています。お手柔らかに)
サンプルコード
require 'open-uri' # URLにアクセスするためのライブラリの読み込み
require 'csv' # CSV出力をできるようにするためのライブラリ
namespace :scrape do
desc 'アサインナビhintのinterviewページから、各記事のタイトルやURLを取得し、CSVで書き出し'
task :anavihint_title_url => :environment do
# スクレイピング先のURL
url = ''
charset = nil
begin
html = open(url) do |f|
charset = f.charset # 文字種別を取得
f.read # htmlを読み込んで変数htmlに渡す
end
rescue => e
puts e # 例外メッセージ表示
end
# htmlをパース(解析)してオブジェクトを作成後、csvデータを生成
header = ['title', 'URL', 'Post_Date']
rows = []
rows << header
doc = Nokogiri::HTML.parse(html, nil, charset)
doc.xpath("/html/body/div[2]/div/main/div/article[contains(@class, 'col-item-interview')]").each do |node|
# タイトルとURLの取得
title = node.css('h2').inner_text
url = node.css('a').attribute('href').value
post_date = node.css('time').attribute('datetime').value
rows << [title, url, post_date]
end
# csv書き出し
CSV.open("anavihint_interview_list.csv","w",:force_quotes=>true) do |csv|
rows.each do |row|
csv << row
end
end
end
end
参考文献
■require 'open-uri'
https://qiita.com/tearoom6/items/8d3cb67a1bc4e454e989
https://qiita.com/kumamonmaster/items/9bb2aadde56c956fdc9f
■require 'csv'
https://docs.ruby-lang.org/ja/latest/class/CSV.html
■xpathの書き方
https://qiita.com/rllllho/items/cb1187cec0fb17fc650a
■gem 'nokogiri'
・Nokogiriの検索・参照系メソッド
https://qiita.com/Kenya/items/d1a2325a552d11814111
・WebスクレイピングのためのCSSセレクタの基本
https://gammasoft.jp/support/css-selector-for-python-web-scraping/
・任意の情報を抜き出す
TBD