Class: Crawlscope::Browser

Inherits:
Object
  • Object
show all
Defined in:
lib/crawlscope/browser.rb

Instance Method Summary collapse

Constructor Details

#initialize(base_url:, timeout_seconds:, network_idle_timeout_seconds:, scroll_page:) ⇒ Browser

Returns a new instance of Browser.



7
8
9
10
11
12
13
14
# File 'lib/crawlscope/browser.rb', line 7

def initialize(base_url:, timeout_seconds:, network_idle_timeout_seconds:, scroll_page:)
  @base_url = base_url
  @timeout_seconds = timeout_seconds
  @network_idle_timeout_seconds = network_idle_timeout_seconds
  @scroll_page = scroll_page
  @browser = build_browser
  @page = @browser.create_page
end

Instance Method Details

#closeObject



16
17
18
# File 'lib/crawlscope/browser.rb', line 16

def close
  @browser&.quit
end

#fetch(url) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/crawlscope/browser.rb', line 20

def fetch(url)
  @page.network.clear(:traffic)
  @page.go_to(url)
  wait_for_network_idle

  if @scroll_page
    scroll_for_render
  end

  response = @page.network.response
  final_url = response&.url.to_s
  final_url = @page.current_url.to_s if final_url.empty?
  final_url = @page.url.to_s if final_url.empty?
  final_url = url if final_url.empty?
  headers = response&.headers || {}
  body = @page.body

  Page.new(
    url: url,
    normalized_url: Url.normalize(url, base_url: @base_url),
    final_url: final_url,
    normalized_final_url: Url.normalize(final_url, base_url: @base_url),
    status: @page.network.status,
    headers: headers,
    body: body,
    doc: Nokogiri::HTML(body)
  )
rescue => error
  Page.new(
    url: url,
    normalized_url: Url.normalize(url, base_url: @base_url),
    final_url: url,
    normalized_final_url: Url.normalize(url, base_url: @base_url),
    status: nil,
    headers: {},
    body: nil,
    doc: nil,
    error: "#{error.class}: #{error.message}"
  )
end