Class: Crawlscope::Http
- Inherits:
-
Object
- Object
- Crawlscope::Http
- 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
- #close ⇒ Object
- #fetch(url) ⇒ Object
-
#initialize(base_url:, timeout_seconds:, adapter: nil) ⇒ Http
constructor
A new instance of Http.
Constructor Details
#initialize(base_url:, timeout_seconds:, adapter: nil) ⇒ Http
Returns a new instance of Http.
13 14 15 16 17 18 |
# File 'lib/crawlscope/http.rb', line 13 def initialize(base_url:, timeout_seconds:, adapter: nil) @base_url = base_url @timeout_seconds = timeout_seconds @adapter = adapter @connections_by_thread = Concurrent::Map.new end |
Instance Method Details
#close ⇒ Object
20 21 22 23 24 25 26 |
# File 'lib/crawlscope/http.rb', line 20 def close @connections_by_thread.each_value do |connection| connection.close if connection.respond_to?(:close) end @connections_by_thread.clear end |
#fetch(url) ⇒ Object
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 60 61 62 63 |
# File 'lib/crawlscope/http.rb', line 28 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 Faraday::Error, SocketError, SystemCallError, Timeout::Error => 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.}" ) end |