1
0

url_scraper.rb 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. module Docs
  2. class UrlScraper < Scraper
  3. class << self
  4. attr_accessor :params
  5. attr_accessor :headers
  6. def inherited(subclass)
  7. super
  8. subclass.params = params.deep_dup
  9. subclass.headers = headers.deep_dup
  10. end
  11. end
  12. self.params = {}
  13. self.headers = { 'User-Agent' => 'DevDocs' }
  14. private
  15. def request_one(url)
  16. Request.run url, request_options
  17. end
  18. def request_all(urls, &block)
  19. Requester.run urls, request_options: request_options, &block
  20. end
  21. def request_options
  22. { params: self.class.params, headers: self.class.headers }
  23. end
  24. def process_response?(response)
  25. if response.error?
  26. raise "Error status code (#{response.code}): #{response.url}"
  27. end
  28. response.success? && response.html? && process_url?(response.effective_url)
  29. end
  30. def process_url?(url)
  31. base_url.contains?(url)
  32. end
  33. def load_capybara_selenium
  34. require 'capybara/dsl'
  35. Capybara.register_driver :selenium_marionette do |app|
  36. Capybara::Selenium::Driver.new(app, marionette: true)
  37. end
  38. Capybara.current_driver = :selenium_marionette
  39. Capybara.run_server = false
  40. Capybara
  41. end
  42. module FixRedirectionsBehavior
  43. def self.included(base)
  44. base.extend ClassMethods
  45. end
  46. module ClassMethods
  47. attr_reader :redirections
  48. def store_pages(store)
  49. instrument 'info.doc', msg: 'Fetching redirections...'
  50. with_redirections do
  51. instrument 'info.doc', msg: 'Building pages...'
  52. super
  53. end
  54. end
  55. private
  56. def with_redirections
  57. @redirections = new.fetch_redirections
  58. yield
  59. ensure
  60. @redirections = nil
  61. end
  62. end
  63. def fetch_redirections
  64. result = {}
  65. with_filters 'container', 'normalize_urls', 'internal_urls' do
  66. build_pages do |page|
  67. next if page[:response_effective_path] == page[:response_path]
  68. result[page[:response_path].downcase] = page[:response_effective_path]
  69. end
  70. end
  71. result
  72. end
  73. private
  74. def process_response(response)
  75. super.merge! response_effective_path: response.effective_path, response_path: response.path
  76. end
  77. def additional_options
  78. { redirections: self.class.redirections }
  79. end
  80. end
  81. end
  82. end