scraper.rb 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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. puts "URL: #{response.url}"
  133. raise e
  134. end
  135. def process_response(response)
  136. data = {}
  137. pipeline.call(parse(response.body), pipeline_context(response), data)
  138. data
  139. end
  140. def pipeline_context(response)
  141. options.merge url: response.url
  142. end
  143. def parse(string)
  144. Parser.new(string).html
  145. end
  146. def with_filters(*filters)
  147. stack = FilterStack.new
  148. stack.push(*filters)
  149. pipeline.instance_variable_set :@filters, stack.to_a.freeze
  150. yield
  151. ensure
  152. @pipeline = nil
  153. end
  154. module StubRootPage
  155. private
  156. def request_one(url)
  157. stub_root_page if url == root_url.to_s
  158. super
  159. end
  160. def request_all(urls, &block)
  161. stub_root_page
  162. super
  163. end
  164. def stub_root_page
  165. response = Typhoeus::Response.new(
  166. effective_url: root_url.to_s,
  167. code: 200,
  168. headers: { 'Content-Type' => 'text/html' },
  169. body: root_page_body)
  170. Typhoeus.stub(root_url.to_s).and_return(response)
  171. end
  172. end
  173. module FixInternalUrlsBehavior
  174. def self.included(base)
  175. base.extend ClassMethods
  176. end
  177. module ClassMethods
  178. attr_reader :internal_urls
  179. def store_pages(store)
  180. instrument 'info.doc', msg: 'Building internal urls...'
  181. with_internal_urls do
  182. instrument 'info.doc', msg: 'Building pages...'
  183. super
  184. end
  185. end
  186. private
  187. def with_internal_urls
  188. @internal_urls = new.fetch_internal_urls
  189. yield
  190. ensure
  191. @internal_urls = nil
  192. end
  193. end
  194. def fetch_internal_urls
  195. result = []
  196. build_pages do |page|
  197. result << base_url.subpath_to(page[:response_url]) if page[:entries].present?
  198. end
  199. result
  200. end
  201. def initial_urls
  202. return super unless self.class.internal_urls
  203. @initial_urls ||= self.class.internal_urls.map(&method(:url_for)).freeze
  204. end
  205. private
  206. def additional_options
  207. if self.class.internal_urls
  208. {
  209. only: self.class.internal_urls.to_set,
  210. only_patterns: nil,
  211. skip: nil,
  212. skip_patterns: nil,
  213. skip_links: nil,
  214. fixed_internal_urls: true
  215. }
  216. else
  217. {}
  218. end
  219. end
  220. def process_response(response)
  221. super.merge! response_url: response.url
  222. end
  223. end
  224. end
  225. end