hybrid_scraper 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,230 @@
1
+ require "net/http"
2
+ require "uri"
3
+ require "time"
4
+ require "resolv"
5
+ require "ipaddr"
6
+ require "hybrid_scraper/user_agent"
7
+ require "hybrid_scraper/url_validator"
8
+ require "hybrid_scraper/logger"
9
+
10
+ module HybridScraper
11
+ module Fetchers
12
+ class StaticFetcher
13
+ def initialize(config)
14
+ @config = config
15
+ @cookie_jar = {}
16
+ @jar_mutex = Mutex.new
17
+ end
18
+
19
+ def fetch(url, cookies: {}, headers: {})
20
+ current_url = url
21
+ redirects = 0
22
+
23
+ loop do
24
+ UrlValidator.validate!(current_url, allow_private: @config.allow_private_urls)
25
+
26
+ uri = URI.parse(current_url)
27
+ host = uri.host
28
+ ip = resolve_and_validate_ip(host, uri.scheme)
29
+
30
+ merged_headers = build_headers(current_url, cookies, headers, uri)
31
+ response = perform_request(uri, ip, merged_headers)
32
+
33
+ store_cookies_from_response(response, uri.host)
34
+
35
+ if redirect_response?(response)
36
+ redirects += 1
37
+ if redirects > @config.max_redirects
38
+ raise HybridScraper::Error, "Too many redirects for #{url}"
39
+ end
40
+
41
+ location = response["location"]&.first || response["location"]
42
+ raise HybridScraper::Error, "Redirect without Location for #{current_url}" if location.nil? || location.empty?
43
+
44
+ current_url = URI.join(current_url, location).to_s
45
+ Logger.debug(@config, "Redirecting to #{current_url}")
46
+ next
47
+ end
48
+
49
+ status = response.code.to_i
50
+ unless (200..299).cover?(status)
51
+ raise HybridScraper::HTTPError, "HTTP #{status} for #{current_url}"
52
+ end
53
+
54
+ return response.body
55
+ end
56
+ end
57
+
58
+ private
59
+
60
+ def resolve_and_validate_ip(host, scheme)
61
+ return nil if @config.allow_private_urls
62
+
63
+ ip = Resolv.getaddress(host)
64
+ addr = IPAddr.new(ip)
65
+ if addr.private? || addr.loopback? || addr.link_local? || ip == "169.254.169.254"
66
+ raise HybridScraper::Error, "Blocked resolved address for #{host}"
67
+ end
68
+ ip
69
+ rescue Resolv::ResolvError => e
70
+ raise HybridScraper::NetworkError, "DNS resolution failed for #{host}: #{e.message}"
71
+ end
72
+
73
+ def perform_request(uri, ip, headers)
74
+ address = ip || uri.host
75
+ http = Net::HTTP.new(address, uri.port)
76
+ http.use_ssl = (uri.scheme == "https")
77
+ http.open_timeout = @config.open_timeout
78
+ http.read_timeout = @config.timeout
79
+ http.verify_hostname = uri.host if http.respond_to?(:verify_hostname=)
80
+
81
+ # Proxy support
82
+ if @config.proxy
83
+ proxy_uri = URI.parse(@config.proxy)
84
+ http = Net::HTTP.new(address, uri.port, proxy_uri.host, proxy_uri.port, @config.proxy_username, @config.proxy_password)
85
+ http.use_ssl = (uri.scheme == "https")
86
+ http.open_timeout = @config.open_timeout
87
+ http.read_timeout = @config.timeout
88
+ http.verify_hostname = uri.host if http.respond_to?(:verify_hostname=)
89
+ end
90
+
91
+ request = Net::HTTP::Get.new(uri.request_uri)
92
+ headers.each { |k, v| request[k] = v }
93
+
94
+ http.request(request)
95
+ rescue Net::OpenTimeout, Net::ReadTimeout, Timeout::Error => e
96
+ raise HybridScraper::TimeoutError, "Timeout fetching #{uri}: #{e.message}"
97
+ rescue StandardError => e
98
+ raise HybridScraper::NetworkError, "Network error fetching #{uri}: #{e.message}"
99
+ end
100
+
101
+ def redirect_response?(response)
102
+ [301, 302, 303, 307, 308].include?(response.code.to_i)
103
+ end
104
+
105
+ def build_headers(url, cookies, headers, uri)
106
+ h = { "User-Agent" => current_user_agent }
107
+ h.merge!(@config.headers || {})
108
+ h.merge!(headers || {})
109
+
110
+ cookie_str = build_cookie_string(url, cookies, uri)
111
+ h["Cookie"] = cookie_str unless cookie_str.empty?
112
+
113
+ h
114
+ end
115
+
116
+ def build_cookie_string(url, cookies, uri)
117
+ host = uri.host
118
+ secure = uri.scheme == "https"
119
+ path = uri.path.empty? ? "/" : uri.path
120
+
121
+ merged = {}
122
+
123
+ global = @config.cookies || {}
124
+ if global.values.all? { |v| v.is_a?(Hash) }
125
+ global.each do |domain, cks|
126
+ if domain.to_s == "*" || domain.to_s == host || host&.end_with?(domain.to_s)
127
+ (cks || {}).each { |k, v| merged[k] = normalize_cookie(v, path) }
128
+ end
129
+ end
130
+ else
131
+ (global || {}).each { |k, v| merged[k] = normalize_cookie(v, path) }
132
+ end
133
+
134
+ @jar_mutex.synchronize do
135
+ @cookie_jar.each do |domain, cookies_for_domain|
136
+ next unless host == domain || host&.end_with?(domain.to_s.sub(/\A\./, ""))
137
+ cookies_for_domain.each do |name, cookie|
138
+ next unless cookie_usable?(cookie, path, secure)
139
+ merged[name] = cookie[:value]
140
+ end
141
+ end
142
+ end
143
+
144
+ (cookies || {}).each { |k, v| merged[k] = v }
145
+ merged.map { |k, v| "#{k}=#{v}" }.join("; ")
146
+ end
147
+
148
+ def normalize_cookie(value, _path)
149
+ value.is_a?(Hash) ? value[:value] : value
150
+ end
151
+
152
+ def cookie_usable?(cookie, path, secure)
153
+ return false if cookie[:expires] && Time.now > cookie[:expires]
154
+ return false if cookie[:secure] && !secure
155
+ return false unless path_matches?(cookie[:path] || "/", path)
156
+ true
157
+ end
158
+
159
+ def path_matches?(cookie_path, request_path)
160
+ return true if cookie_path == "/"
161
+ request_path.start_with?(cookie_path)
162
+ end
163
+
164
+ def current_user_agent
165
+ if @config.rotate_user_agent
166
+ UserAgent.pick(@config)
167
+ else
168
+ @config.user_agent
169
+ end
170
+ end
171
+
172
+ def store_cookies_from_response(response, host)
173
+ raw = response["set-cookie"]
174
+ return if raw.nil?
175
+
176
+ Array(raw).each do |header|
177
+ header.to_s.split("\n").each do |line|
178
+ parse_and_store_cookie(line, host)
179
+ end
180
+ end
181
+ rescue StandardError
182
+ end
183
+
184
+ def parse_and_store_cookie(line, default_host)
185
+ return if line.nil? || line.strip.empty?
186
+ parts = line.split(";").map(&:strip)
187
+ name_value = parts.first
188
+ return unless name_value && name_value.include?("=")
189
+
190
+ name, value = name_value.split("=", 2)
191
+ return if name.nil? || name.strip.empty?
192
+
193
+ attrs = {}
194
+ parts[1..].each do |attr|
195
+ key, val = attr.split("=", 2)
196
+ key = key.to_s.strip.downcase
197
+ val = val.to_s.strip
198
+ case key
199
+ when "domain" then attrs[:domain] = val.sub(/\A\./, "")
200
+ when "path" then attrs[:path] = val.empty? ? "/" : val
201
+ when "expires" then attrs[:expires] = parse_time(val)
202
+ when "max-age" then attrs[:expires] = Time.now + val.to_i
203
+ when "secure" then attrs[:secure] = true
204
+ when "httponly" then attrs[:http_only] = true
205
+ end
206
+ end
207
+
208
+ domain = attrs[:domain] || default_host
209
+ cookie = {
210
+ value: value.to_s,
211
+ path: attrs[:path] || "/",
212
+ expires: attrs[:expires],
213
+ secure: attrs[:secure] || false,
214
+ http_only: attrs[:http_only] || false
215
+ }
216
+
217
+ @jar_mutex.synchronize do
218
+ @cookie_jar[domain] ||= {}
219
+ @cookie_jar[domain][name.strip] = cookie
220
+ end
221
+ end
222
+
223
+ def parse_time(value)
224
+ Time.parse(value)
225
+ rescue StandardError
226
+ nil
227
+ end
228
+ end
229
+ end
230
+ end
@@ -0,0 +1,41 @@
1
+ module HybridScraper
2
+ module Logger
3
+ LEVELS = { debug: 0, info: 1, warn: 2, error: 3 }.freeze
4
+
5
+ SENSITIVE_PATTERNS = [
6
+ /([?&][^=\s]+)=([^&\s]+)/, # URL query params
7
+ /(password|passwd|pwd|secret|token|api[_-]?key)=\S+/i,
8
+ /(authorization:\s*bearer\s+)\S+/i
9
+ ].freeze
10
+
11
+ def self.redact(message)
12
+ text = message.to_s
13
+ SENSITIVE_PATTERNS.each do |pattern|
14
+ text = text.gsub(pattern) do |match|
15
+ if match.include?("=") && !match.downcase.include?("bearer")
16
+ key = match.split("=", 2)[0]
17
+ "#{key}=[REDACTED]"
18
+ elsif match.downcase.include?("bearer")
19
+ match.sub(/\S+\z/, "[REDACTED]")
20
+ else
21
+ "[REDACTED]"
22
+ end
23
+ end
24
+ end
25
+ text
26
+ end
27
+
28
+ def self.log(config, level, message)
29
+ threshold = LEVELS.fetch(config.log_level, 1)
30
+ return if LEVELS.fetch(level, 1) < threshold
31
+
32
+ prefix = "[HybridScraper][#{level.upcase}]"
33
+ warn "#{prefix} #{redact(message)}"
34
+ end
35
+
36
+ def self.debug(config, message); log(config, :debug, message); end
37
+ def self.info(config, message); log(config, :info, message); end
38
+ def self.warn(config, message); log(config, :warn, message); end
39
+ def self.error(config, message); log(config, :error, message); end
40
+ end
41
+ end
@@ -0,0 +1,10 @@
1
+ module HybridScraper
2
+ module Middleware
3
+ # Base class for middleware. Override hooks as needed.
4
+ class Base
5
+ def before_request(url, context); end
6
+ def after_response(result, context); end
7
+ def on_error(error, context); end
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,51 @@
1
+ require "nokogiri"
2
+
3
+ module HybridScraper
4
+ class Result
5
+ attr_reader :url, :html, :mode
6
+
7
+ def initialize(url, html, mode)
8
+ @url = url
9
+ @html = html
10
+ @mode = mode
11
+ @doc = Nokogiri::HTML(html)
12
+ end
13
+
14
+ def doc
15
+ @doc
16
+ end
17
+
18
+ def css(selector)
19
+ @doc.css(selector)
20
+ end
21
+
22
+ def xpath(selector)
23
+ @doc.xpath(selector)
24
+ end
25
+
26
+ def text(selector)
27
+ @doc.css(selector).map { |n| n.text.strip }.reject(&:empty?)
28
+ end
29
+
30
+ # fields: { name => css_selector_or_proc }
31
+ def extract(fields = {})
32
+ fields.each_with_object({}) do |(name, selector), out|
33
+ if selector.is_a?(Proc)
34
+ out[name] = selector.call(@doc)
35
+ else
36
+ nodes = @doc.css(selector.to_s)
37
+ out[name] = nodes.size > 1 ? nodes.map { |n| n.text.strip } : nodes.first&.text&.strip
38
+ end
39
+ end
40
+ end
41
+
42
+ def to_h
43
+ { url: @url, mode: @mode }
44
+ end
45
+
46
+ def to_json(*args)
47
+ require "json"
48
+ to_h.merge(html: @html).to_json(*args)
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,152 @@
1
+ require "net/http"
2
+ require "uri"
3
+ require "ipaddr"
4
+ require "resolv"
5
+
6
+ module HybridScraper
7
+ module Robots
8
+ def self.resolve_ip(host)
9
+ Resolv.getaddress(host)
10
+ rescue StandardError
11
+ nil
12
+ end
13
+ @cache = {}
14
+ @mutex = Mutex.new
15
+
16
+ def self.allowed?(url, user_agent: "*")
17
+ group = cached_group(url, user_agent)
18
+ return true unless group
19
+
20
+ evaluate_group(group, URI.parse(url))
21
+ end
22
+
23
+ def self.crawl_delay(url, user_agent: "*")
24
+ group = cached_group(url, user_agent)
25
+ return nil unless group
26
+ group[:crawl_delay]
27
+ end
28
+
29
+ def self.cached_group(url, user_agent)
30
+ uri = URI.parse(url)
31
+ key = "#{uri.scheme}://#{uri.host}:#{uri.port}"
32
+
33
+ @mutex.synchronize do
34
+ @cache[key] ||= fetch_and_parse(uri, user_agent)
35
+ end
36
+ end
37
+
38
+ def self.fetch_and_parse(uri, user_agent)
39
+ robots_uri = uri.dup
40
+ robots_uri.path = "/robots.txt"
41
+ robots_uri.query = nil
42
+ robots_uri.fragment = nil
43
+
44
+ UrlValidator.validate!(robots_uri.to_s, allow_private: false) rescue nil
45
+
46
+ ip = resolve_ip(robots_uri.host)
47
+ if ip
48
+ addr = IPAddr.new(ip)
49
+ raise "blocked" if addr.private? || addr.loopback? || addr.link_local?
50
+ end
51
+
52
+ http = Net::HTTP.new(ip || robots_uri.host, robots_uri.port)
53
+ http.use_ssl = (robots_uri.scheme == "https")
54
+ http.open_timeout = 10
55
+ http.read_timeout = 10
56
+ http.verify_hostname = robots_uri.host if http.respond_to?(:verify_hostname=)
57
+
58
+ response = http.get(robots_uri.request_uri)
59
+ return nil unless response.is_a?(Net::HTTPSuccess)
60
+
61
+ groups = parse_groups(response.body)
62
+ matching_group(groups, user_agent)
63
+ rescue StandardError
64
+ nil
65
+ end
66
+
67
+ def self.evaluate_group(group, uri)
68
+ path = uri.path.empty? ? "/" : uri.path
69
+ rules = group[:rules].sort_by { |r| -r[:pattern].length }
70
+
71
+ best = nil
72
+ rules.each do |rule|
73
+ next unless wildcard_match?(rule[:pattern], path)
74
+ if best.nil? || rule[:pattern].length > best[:pattern].length ||
75
+ (rule[:pattern].length == best[:pattern].length && rule[:type] == :allow)
76
+ best = rule
77
+ end
78
+ end
79
+
80
+ return true if best.nil?
81
+ best[:type] == :allow
82
+ end
83
+
84
+ def self.evaluate(body, uri, user_agent)
85
+ groups = parse_groups(body)
86
+ group = matching_group(groups, user_agent)
87
+ return true unless group
88
+
89
+ path = uri.path.empty? ? "/" : uri.path
90
+ rules = group[:rules].sort_by { |r| -r[:pattern].length }
91
+
92
+ # Longest (and most specific) match wins; Allow wins ties.
93
+ best = nil
94
+ rules.each do |rule|
95
+ next unless wildcard_match?(rule[:pattern], path)
96
+ if best.nil? || rule[:pattern].length > best[:pattern].length ||
97
+ (rule[:pattern].length == best[:pattern].length && rule[:type] == :allow)
98
+ best = rule
99
+ end
100
+ end
101
+
102
+ return true if best.nil?
103
+ best[:type] == :allow
104
+ end
105
+
106
+ def self.parse_groups(body)
107
+ groups = []
108
+ current = nil
109
+
110
+ body.each_line do |raw|
111
+ line = raw.strip
112
+ next if line.empty? || line.start_with?("#")
113
+
114
+ key, value = line.split(":", 2)
115
+ next unless key && value
116
+ key = key.strip.downcase
117
+ value = value.strip
118
+
119
+ case key
120
+ when "user-agent"
121
+ current = { agents: [value], rules: [], crawl_delay: nil }
122
+ groups << current
123
+ when "allow", "disallow"
124
+ next unless current
125
+ current[:rules] << { type: key.to_sym, pattern: value }
126
+ when "crawl-delay"
127
+ current[:crawl_delay] = value.to_f if current
128
+ next
129
+ end
130
+ end
131
+
132
+ groups
133
+ end
134
+
135
+ def self.matching_group(groups, user_agent)
136
+ ua = user_agent.to_s.downcase
137
+ groups.find do |g|
138
+ g[:agents].any? { |a| a == "*" || a.downcase == ua }
139
+ end
140
+ end
141
+
142
+ def self.wildcard_match?(pattern, path)
143
+ return true if pattern.nil? || pattern.empty?
144
+
145
+ anchored = pattern.end_with?("$")
146
+ p = anchored ? pattern[0...-1] : pattern
147
+ regex_str = Regexp.escape(p).gsub("\\*", ".*")
148
+ regex = anchored ? /\A#{regex_str}\z/ : /\A#{regex_str}/
149
+ regex.match?(path)
150
+ end
151
+ end
152
+ end
@@ -0,0 +1,45 @@
1
+ require "uri"
2
+ require "ipaddr"
3
+ require "resolv"
4
+
5
+ module HybridScraper
6
+ module UrlValidator
7
+ BLOCKED_HOSTS = %w[localhost].freeze
8
+ METADATA_IP = "169.254.169.254".freeze
9
+
10
+ def self.validate!(url, allow_private: false)
11
+ uri = URI.parse(url.to_s)
12
+ raise HybridScraper::Error, "Invalid URL: #{url}" unless uri.is_a?(URI::HTTP) || uri.is_a?(URI::HTTPS)
13
+ raise HybridScraper::Error, "URL must use http or https" unless %w[http https].include?(uri.scheme)
14
+ raise HybridScraper::Error, "URL host is missing" if uri.host.nil? || uri.host.empty?
15
+
16
+ host = uri.host.downcase
17
+ return if allow_private
18
+
19
+ raise HybridScraper::Error, "Blocked host: #{host}" if BLOCKED_HOSTS.include?(host) || host.end_with?(".local")
20
+
21
+ ip = resolve_ip(host)
22
+ if ip
23
+ addr = IPAddr.new(ip)
24
+ raise HybridScraper::Error, "Blocked private or metadata address" if private_or_metadata?(addr)
25
+ end
26
+
27
+ true
28
+ rescue URI::InvalidURIError => e
29
+ raise HybridScraper::Error, "Invalid URL: #{e.message}"
30
+ end
31
+
32
+ def self.resolve_ip(host)
33
+ Resolv.getaddress(host)
34
+ rescue StandardError
35
+ nil
36
+ end
37
+
38
+ def self.private_or_metadata?(addr)
39
+ return true if addr.to_s == METADATA_IP
40
+ addr.private? || addr.loopback? || addr.link_local?
41
+ rescue StandardError
42
+ false
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,14 @@
1
+ module HybridScraper
2
+ module UserAgent
3
+ DEFAULTS = [
4
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
5
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15",
6
+ "Mozilla/5.0 (X11; Linux x86_64; rv:125.0) Gecko/20100101 Firefox/125.0"
7
+ ].freeze
8
+
9
+ def self.pick(config)
10
+ pool = config.user_agents.empty? ? DEFAULTS : config.user_agents
11
+ pool.sample
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,3 @@
1
+ module HybridScraper
2
+ VERSION = "0.1.1"
3
+ end
@@ -0,0 +1,25 @@
1
+ require "hybrid_scraper/version"
2
+ require "hybrid_scraper/configuration"
3
+ require "hybrid_scraper/logger"
4
+ require "hybrid_scraper/middleware"
5
+ require "hybrid_scraper/user_agent"
6
+ require "hybrid_scraper/result"
7
+ require "hybrid_scraper/client"
8
+ require "hybrid_scraper/exporter"
9
+ require "hybrid_scraper/robots"
10
+ require "hybrid_scraper/url_validator"
11
+
12
+ module HybridScraper
13
+ class Error < StandardError; end
14
+ class NetworkError < Error; end
15
+ class HTTPError < Error; end
16
+ class TimeoutError < Error; end
17
+ class BrowserError < Error; end
18
+
19
+ autoload :StaticFetcher, "hybrid_scraper/fetchers/static_fetcher"
20
+ autoload :BrowserFetcher, "hybrid_scraper/fetchers/browser_fetcher"
21
+
22
+ def self.client(config = configuration)
23
+ Client.new(config)
24
+ end
25
+ end