通常、多くの Web サイトで同じである css セレクターに基づいてデータを抽出する「一般的な」メソッドがいくつかあります。ただし、特定の Web サイトの css セレクターを引数として受け入れる別のメソッドがあります。
title_selector 引数が渡されない場合は、get_title メソッドを呼び出す必要があります。どうやってやるの?
cssセレクターを引数として受け入れるスクレイプ
def scrape(urls, item_selector, title_selector, price_selector, image_selector)
collection = []
urls.each do |url|
doc = Nokogiri::HTML(open(url).read) # Opens URL
@items = doc.css(item_selector)[0..1].map {|item| item['href']} # Sets items
@items.each do |item| # Donwload each link and parse
page = Nokogiri::HTML(open(item).read)
collection << {
:title => page.css(title_selector).text, # I guess I need conditional here
:price => page.css(price_selector).text
}
end
@collection = collection
end
end
ジェネリック タイトル エクストラクタ
def get_title(doc)
if doc.at_css("meta[property='og:title']")
title = doc.css("meta[property='og:title']")
else doc.css('title')
title = doc.at_css('title').text
end
end