Class: Crawlscope::Http

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

Constant Summary collapse

MAX_REDIRECTS =
5
USER_AGENT =
"Mozilla/5.0 (compatible; Crawlscope/1.0)"

Instance Method Summary collapse

Constructor Details

#initialize(base_url:, timeout_seconds:) ⇒ Http

Returns a new instance of Http.



13
14
15
16
17
# File 'lib/crawlscope/http.rb', line 13

def initialize(base_url:, timeout_seconds:)
  @base_url = base_url
  @timeout_seconds = timeout_seconds
  @connections_by_thread = Concurrent::Map.new
end

Instance Method Details

#closeObject



19
20
21
# File 'lib/crawlscope/http.rb', line 19

def close
  @connections_by_thread.clear
end

#fetch(url) ⇒ Object



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
# File 'lib/crawlscope/http.rb', line 23

def fetch(url)
  response = connection.get(url) do |request|
    request.headers["User-Agent"] = USER_AGENT
  end

  final_url = response.env.url.to_s
  final_url = url if final_url.empty?
  headers = response.headers.to_h
  body = response.body.to_s
  doc = if response.status == 200 && html_response?(headers)
    Nokogiri::HTML(body)
  end

  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: response.status,
    headers: headers,
    body: body,
    doc: doc
  )
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