Rubyの本を初めて読んだ時、self や Proc と並んで意味が全くわからなかったアクセスメソッドの意味と使い方がなんとなくわかった気がしたのでメモ。
いろいろなサイトをスクレイピングしていて、今回はこんなコードを書いてみた。
require 'open-uri'
require 'nokogiri'
require 'kconv'
class HogeBot
URL_BASE = "https://hogehoge.com/"
UserAgnet = "Mozilla/5.0 () "
attr_accessor :next_url
def initialize
@next_url = "https://hogehoge.com/hoge/?page=2"
@page_number = 2
@image = []
@title = []
@author = []
end
# ネクストページのコンテンツが nil になるまで繰り返し
def check_page
open_url while @next_url
end
# URLを open して get_content を実行後、次のページを next_url に代入
def open_url
sleep 1
p @next_url
html = open(@next_url,"User-Agent" => UserAgnet).read
doc = Nokogiri::HTML(html.toutf8, nil, 'utf-8')
get_content(doc)
# ページコンテンツが無かった場合、nil を返す。
@next_url = if doc.css(".hogehogehoge").empty?
nil
else
@page_number += 1
URL_BASE + "?page=" + @page_number.to_s
end
end
# ページコンテンツを取得
def get_content(doc)
doc.css(".hogehoge").each do |row|
@image.push img_src = row.css("img").attribute("src").value
@title.push row.css("h1").text
@author.push row.css("h2").text
end
end
end
やってることは下のようなリンク構造を持ち、コンテンツは無くてもpage 自体は用意してあるようなサイトから情報を抜き出してくること。
https://hogehoge.com/hoge/?page=2
https://hogehoge.com/hoge/?page=3
https://hogehoge.com/hoge/?page=4
https://hogehoge.com/hoge/?page=5
https://hogehoge.com/hoge/?page=6
https://hogehoge.com/hoge/?page=100 #ページはあるけどコンテンツは空
コード内に self とか attr_accessor が書いてあるが、意味はあまり良くわからずに使っている。
でコードを書いた後に、@title
, @image
, @author
を取り出そうとして困った。どうやって取り出せばいいんだろう。
hoge_scrape = HogeBot.new
hoge_scrape.check_page
これでプログラムが動いて、@title
, @image
, @author
の配列に情報が入っているはずなのに。。。
そんな時にこの記事を見てようやくなんとなくの使い方がわかった。
require 'open-uri'
require 'nokogiri'
require 'kconv'
class HogeBot
URL_BASE = "https://hogehoge.com/"
UserAgnet = "Mozilla/5.0 () "
#コメントでアドバイスをいただき、修正
attr_accessor :next_url, :image, :title, :author
# attr_accessor :next_url
# attr_accessor :image
# attr_accessor :title
# attr_accessor :author
def initialize
@next_url = "https://hogehoge.com/hoge/?page=2"
@page_number = 2
@image = []
@title = []
@author = []
end
すごいこれで取り出せるなんてすごい便利!
hoge_scrape = HogeBot.new
hoge_scrape.check_page
hoge_scrape.image
hoge_scrape.title
hoge_scrape.author
こんな感じでインスタンス変数とかにアクセスできるんですね!