Skip to content

Instantly share code, notes, and snippets.

@vladimir-vg
Created December 6, 2014 21:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vladimir-vg/396b988216387ed69fc5 to your computer and use it in GitHub Desktop.
Save vladimir-vg/396b988216387ed69fc5 to your computer and use it in GitHub Desktop.
class FooBarVendor::ItemScraper < Scraper
# подключаем самописный DSL для работы с HTML
include Makhno
# присутствие строго одного элемента
one :title,
css: '.product-details .product-content > h1',
# перед manipulate, элемент будет преобразован в значение
value: ->(e) { e.text.strip }
one :description,
css: '.product-details .product-content .descr',
value: ->(e) { e.text.strip }
one :price,
css: '.product-details .product-content .price strong',
value: ->(e) { e.text.strip }
# один либо более элементов
many :images_urls,
optional: true, # послабление: ноль либо более элементов
css: '.product-details .product-images > a',
value: ->(e) { normalize_url(e.attr('href'), @vendor.domain) }
many :no_image_marker,
optional: true,
css: '.product-details .product-images > img',
value: ->(e) { true }
many :breadcrumbs,
css: '.main-content .breadcrumbs li',
value: ->(e) { e.text.strip }
# можно добавить ещё объявлений, описывающих структуру DOM.
# просто чтобы быть уверенным что поставщик ничего не менял.
# Этот метод выполняется только если все элементы найдены и их value вычислен
# если каких-то элементов нет, то воркер падает с ошибкой.
def manipulate
if images_urls.empty?
raise "Images not found, nor placeholder either" unless no_image_marker
build_event(@message, message: 'no-images-for-item', info: true).save!
end
@version.raw = {
title: title,
description: description,
price: price,
category_title: breadcrumbs[-2],
images_urls: images_urls }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment