scraper.rb 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. require 'set'
  2. module Docs
  3. class Scraper < Doc
  4. class << self
  5. attr_accessor :base_url, :root_path, :initial_paths, :options, :html_filters, :text_filters, :stubs
  6. def inherited(subclass)
  7. super
  8. subclass.class_eval do
  9. extend AutoloadHelper
  10. autoload_all "docs/filters/#{to_s.demodulize.underscore}", 'filter'
  11. end
  12. subclass.base_url = base_url
  13. subclass.root_path = root_path
  14. subclass.initial_paths = initial_paths.dup
  15. subclass.options = options.deep_dup
  16. subclass.html_filters = html_filters.inheritable_copy
  17. subclass.text_filters = text_filters.inheritable_copy
  18. subclass.stubs = stubs.dup
  19. end
  20. def filters
  21. html_filters.to_a + text_filters.to_a
  22. end
  23. def stub(path, &block)
  24. @stubs[path] = block
  25. @stubs
  26. end
  27. end
  28. include Instrumentable
  29. self.initial_paths = []
  30. self.options = {}
  31. self.stubs = {}
  32. self.html_filters = FilterStack.new
  33. self.text_filters = FilterStack.new
  34. html_filters.push 'container', 'clean_html', 'normalize_urls', 'internal_urls', 'normalize_paths'
  35. text_filters.push 'inner_html', 'clean_text', 'attribution'
  36. def initialize
  37. super
  38. initialize_stubs
  39. end
  40. def initialize_stubs
  41. self.class.stubs.each do |path, block|
  42. Typhoeus.stub(url_for(path)).and_return do
  43. Typhoeus::Response.new \
  44. effective_url: url_for(path),
  45. code: 200,
  46. headers: { 'Content-Type' => 'text/html' },
  47. body: self.instance_exec(&block)
  48. end
  49. end
  50. end
  51. def build_page(path)
  52. response = request_one url_for(path)
  53. result = handle_response(response)
  54. yield result if block_given?
  55. result
  56. end
  57. def build_pages
  58. history = Set.new initial_urls.map(&:downcase)
  59. instrument 'running.scraper', urls: initial_urls
  60. request_all initial_urls do |response|
  61. next unless data = handle_response(response)
  62. yield data
  63. next unless data[:internal_urls].present?
  64. next_urls = data[:internal_urls].select { |url| history.add?(url.downcase) }
  65. instrument 'queued.scraper', urls: next_urls
  66. next_urls
  67. end
  68. end
  69. def base_url
  70. @base_url ||= URL.parse self.class.base_url
  71. end
  72. def root_url
  73. @root_url ||= root_path? ? URL.parse(File.join(base_url.to_s, root_path)) : base_url.normalize
  74. end
  75. def root_path
  76. self.class.root_path
  77. end
  78. def root_path?
  79. root_path.present? && root_path != '/'
  80. end
  81. def initial_paths
  82. self.class.initial_paths
  83. end
  84. def initial_urls
  85. @initial_urls ||= [root_url.to_s].concat(initial_paths.map(&method(:url_for))).freeze
  86. end
  87. def pipeline
  88. @pipeline ||= ::HTML::Pipeline.new(self.class.filters).tap do |pipeline|
  89. pipeline.instrumentation_service = Docs
  90. end
  91. end
  92. def options
  93. @options ||= self.class.options.deep_dup.tap do |options|
  94. options.merge! base_url: base_url, root_url: root_url,
  95. root_path: root_path, initial_paths: initial_paths
  96. if root_path?
  97. (options[:skip] ||= []).concat ['', '/']
  98. end
  99. if options[:only] || options[:only_patterns]
  100. (options[:only] ||= []).concat initial_paths + (root_path? ? [root_path] : ['', '/'])
  101. end
  102. options.merge!(additional_options) if respond_to?(:additional_options, true)
  103. options.freeze
  104. end
  105. end
  106. private
  107. def request_one(url)
  108. raise NotImplementedError
  109. end
  110. def request_all(url, &block)
  111. raise NotImplementedError
  112. end
  113. def process_response?(response)
  114. raise NotImplementedError
  115. end
  116. def url_for(path)
  117. if path.empty? || path == '/'
  118. root_url.to_s
  119. else
  120. File.join(base_url.to_s, path)
  121. end
  122. end
  123. def handle_response(response)
  124. if process_response?(response)
  125. instrument 'process_response.scraper', response: response do
  126. process_response(response)
  127. end
  128. else
  129. instrument 'ignore_response.scraper', response: response
  130. end
  131. rescue => e
  132. if Docs.rescue_errors
  133. instrument 'error.doc', exception: e, url: response.url
  134. nil
  135. else
  136. raise e
  137. end
  138. end
  139. def process_response(response)
  140. data = {}
  141. html, title = parse(response.body)
  142. context = pipeline_context(response)
  143. context[:html_title] = title
  144. pipeline.call(html, context, data)
  145. data
  146. end
  147. def pipeline_context(response)
  148. options.merge url: response.url
  149. end
  150. def parse(string)
  151. parser = Parser.new(string)
  152. [parser.html, parser.title]
  153. end
  154. def with_filters(*filters)
  155. stack = FilterStack.new
  156. stack.push(*filters)
  157. pipeline.instance_variable_set :@filters, stack.to_a.freeze
  158. yield
  159. ensure
  160. @pipeline = nil
  161. end
  162. module FixInternalUrlsBehavior
  163. def self.included(base)
  164. base.extend ClassMethods
  165. end
  166. module ClassMethods
  167. attr_reader :internal_urls
  168. def store_pages(store)
  169. instrument 'info.doc', msg: 'Building internal urls...'
  170. with_internal_urls do
  171. instrument 'info.doc', msg: 'Building pages...'
  172. super
  173. end
  174. end
  175. private
  176. def with_internal_urls
  177. @internal_urls = new.fetch_internal_urls
  178. yield
  179. ensure
  180. @internal_urls = nil
  181. end
  182. end
  183. def fetch_internal_urls
  184. result = []
  185. build_pages do |page|
  186. result << base_url.subpath_to(page[:response_url]) if page[:entries].present?
  187. end
  188. result
  189. end
  190. def initial_urls
  191. return super unless self.class.internal_urls
  192. @initial_urls ||= self.class.internal_urls.map(&method(:url_for)).freeze
  193. end
  194. private
  195. def additional_options
  196. if self.class.internal_urls
  197. {
  198. only: self.class.internal_urls.to_set,
  199. only_patterns: nil,
  200. skip: nil,
  201. skip_patterns: nil,
  202. skip_links: nil,
  203. fixed_internal_urls: true
  204. }
  205. else
  206. {}
  207. end
  208. end
  209. def process_response(response)
  210. super.merge! response_url: response.url
  211. end
  212. end
  213. end
  214. end