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.
- checksums.yaml +7 -0
- data/CHANGELOG.md +7 -0
- data/LICENSE.txt +21 -0
- data/README.md +153 -0
- data/lib/hybrid_scraper/client.rb +173 -0
- data/lib/hybrid_scraper/configuration.rb +61 -0
- data/lib/hybrid_scraper/exporter.rb +48 -0
- data/lib/hybrid_scraper/fetchers/browser_fetcher.rb +169 -0
- data/lib/hybrid_scraper/fetchers/static_fetcher.rb +230 -0
- data/lib/hybrid_scraper/logger.rb +41 -0
- data/lib/hybrid_scraper/middleware.rb +10 -0
- data/lib/hybrid_scraper/result.rb +51 -0
- data/lib/hybrid_scraper/robots.rb +152 -0
- data/lib/hybrid_scraper/url_validator.rb +45 -0
- data/lib/hybrid_scraper/user_agent.rb +14 -0
- data/lib/hybrid_scraper/version.rb +3 -0
- data/lib/hybrid_scraper.rb +25 -0
- metadata +189 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 3e22fb4741b8d7cef4d8bf56b600099ff0a1f888f2de4de9531d6f45e572822e
|
|
4
|
+
data.tar.gz: e59e00045f4db355a65dd7c4ccd6fd7be20790bb218a6ffdcc05a23090a1464c
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 12c26fedb0278226ec0cb16df86deba78c336ce509b1fd14a55fd0bcbe3c9b2a42dbffa5f5a655ad455c91ea8b0eff25d3ac337946ac11b86e2dc761fcb6a571
|
|
7
|
+
data.tar.gz: 2b19646dfb20520973a459212dd5ad4abbbc7c1592a14c61f0873aca8a42d8e6e45330b8ebd0c261bfcd7953722e5230440714be265177ca6a4c45832451fbee
|
data/CHANGELOG.md
ADDED
data/LICENSE.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
# HybridScraper
|
|
2
|
+
|
|
3
|
+
A Ruby library for web scraping that uses **fast static HTTP requests first** and falls back to a **headless browser** only when JavaScript rendering is required.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
gem install hybrid_scraper
|
|
9
|
+
# optional, for JS fallback:
|
|
10
|
+
gem install ferrum
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Or in your `Gemfile`:
|
|
14
|
+
|
|
15
|
+
```ruby
|
|
16
|
+
gem "hybrid_scraper"
|
|
17
|
+
gem "ferrum" # optional
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Usage
|
|
21
|
+
|
|
22
|
+
### Basic fetch
|
|
23
|
+
|
|
24
|
+
```ruby
|
|
25
|
+
require "hybrid_scraper"
|
|
26
|
+
|
|
27
|
+
client = HybridScraper.client
|
|
28
|
+
result = client.fetch("https://example.com")
|
|
29
|
+
|
|
30
|
+
puts result.mode # :static or :browser
|
|
31
|
+
puts result.css("h1").map(&:text)
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
### Force browser fallback with a selector
|
|
35
|
+
|
|
36
|
+
```ruby
|
|
37
|
+
result = client.fetch("https://example.com", selector: ".product-price")
|
|
38
|
+
# If .product-price is missing in static HTML, Ferrum is used.
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
### Force browser fallback with a block
|
|
42
|
+
|
|
43
|
+
```ruby
|
|
44
|
+
result = client.fetch("https://example.com") do |doc|
|
|
45
|
+
doc.css(".product-price").any?
|
|
46
|
+
end
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
### Structured scraping
|
|
50
|
+
|
|
51
|
+
```ruby
|
|
52
|
+
data = client.scrape("https://example.com", {
|
|
53
|
+
title: "h1",
|
|
54
|
+
prices: ".price",
|
|
55
|
+
links: ->(doc) { doc.css("a").map { |a| a["href"] } }
|
|
56
|
+
})
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
### Many URLs
|
|
60
|
+
|
|
61
|
+
```ruby
|
|
62
|
+
rows = client.scrape_many(
|
|
63
|
+
["https://example.com/1", "https://example.com/2"],
|
|
64
|
+
{ title: "h1" }
|
|
65
|
+
)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### Pagination
|
|
69
|
+
|
|
70
|
+
```ruby
|
|
71
|
+
pages = client.paginate(
|
|
72
|
+
"https://example.com/list",
|
|
73
|
+
"a.next",
|
|
74
|
+
limit: 5,
|
|
75
|
+
fields: { title: "h2" }
|
|
76
|
+
)
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
### Configuration
|
|
80
|
+
|
|
81
|
+
```ruby
|
|
82
|
+
HybridScraper.configure do |c|
|
|
83
|
+
c.user_agent = "MyBot/1.0"
|
|
84
|
+
c.timeout = 20
|
|
85
|
+
c.retries = 5
|
|
86
|
+
c.rate_limit = 1.0 # seconds between requests
|
|
87
|
+
c.headless = true
|
|
88
|
+
end
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## Advanced features
|
|
92
|
+
|
|
93
|
+
### Proxy
|
|
94
|
+
|
|
95
|
+
```ruby
|
|
96
|
+
HybridScraper.configure do |c|
|
|
97
|
+
c.proxy = "http://127.0.0.1:8080"
|
|
98
|
+
c.proxy_username = "user"
|
|
99
|
+
c.proxy_password = "pass"
|
|
100
|
+
end
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
### Cookies & headers
|
|
104
|
+
|
|
105
|
+
```ruby
|
|
106
|
+
result = client.fetch("https://example.com", cookies: { session: "abc" }, headers: { "Accept-Language" => "en" })
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### Anti-bot helpers
|
|
110
|
+
|
|
111
|
+
```ruby
|
|
112
|
+
HybridScraper.configure do |c|
|
|
113
|
+
c.rotate_user_agent = true
|
|
114
|
+
c.user_agents = ["Mozilla/5.0 ...", "Mozilla/5.0 ..."]
|
|
115
|
+
c.min_delay = 0.5
|
|
116
|
+
c.max_delay = 2.0
|
|
117
|
+
c.stealth = true
|
|
118
|
+
c.respect_robots = true
|
|
119
|
+
end
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
### Login (form-based)
|
|
123
|
+
|
|
124
|
+
```ruby
|
|
125
|
+
client.login(
|
|
126
|
+
"https://example.com/login",
|
|
127
|
+
username: "me",
|
|
128
|
+
password: "secret",
|
|
129
|
+
username_selector: "input[name='email']",
|
|
130
|
+
password_selector: "input[name='password']"
|
|
131
|
+
)
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
### Export
|
|
135
|
+
|
|
136
|
+
```ruby
|
|
137
|
+
rows = client.scrape_many(urls, { title: "h1" })
|
|
138
|
+
client.export_csv(rows, "out.csv")
|
|
139
|
+
client.export_json(rows, "out.json")
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
## Security, privacy, and terms
|
|
143
|
+
|
|
144
|
+
- Only scrape sites you are allowed to access. Respect `robots.txt` and the target site's Terms of Service.
|
|
145
|
+
- Features like `login`, `stealth`, and `proxy` must be used in accordance with the target site's rules and applicable laws.
|
|
146
|
+
- `stealth` adjusts browser headers/options; it is not intended to bypass anti-bot protections or access controls.
|
|
147
|
+
- Never log or commit secrets. The library redacts common secret patterns in logs, but you are responsible for safe configuration.
|
|
148
|
+
- SSRF protection validates URLs and redirects, but you should still restrict usage to trusted targets.
|
|
149
|
+
|
|
150
|
+
## Notes
|
|
151
|
+
|
|
152
|
+
- Ferrum is a runtime dependency for browser fallback.
|
|
153
|
+
- Prefer official APIs when available.
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
require "uri"
|
|
2
|
+
require "hybrid_scraper/fetchers/static_fetcher"
|
|
3
|
+
require "hybrid_scraper/fetchers/browser_fetcher"
|
|
4
|
+
require "hybrid_scraper/result"
|
|
5
|
+
require "hybrid_scraper/exporter"
|
|
6
|
+
require "hybrid_scraper/robots"
|
|
7
|
+
require "hybrid_scraper/url_validator"
|
|
8
|
+
require "hybrid_scraper/logger"
|
|
9
|
+
|
|
10
|
+
module HybridScraper
|
|
11
|
+
# High-level scraping client.
|
|
12
|
+
#
|
|
13
|
+
# @example
|
|
14
|
+
# client = HybridScraper.client
|
|
15
|
+
# result = client.fetch("https://example.com")
|
|
16
|
+
class Client
|
|
17
|
+
attr_reader :config
|
|
18
|
+
|
|
19
|
+
def initialize(config = HybridScraper.configuration)
|
|
20
|
+
@config = config
|
|
21
|
+
@static = Fetchers::StaticFetcher.new(config)
|
|
22
|
+
@browser = Fetchers::BrowserFetcher.new(config)
|
|
23
|
+
@last_request_at = nil
|
|
24
|
+
@rate_mutex = Mutex.new
|
|
25
|
+
Logger.warn(@config, "allow_private_urls is enabled; use only in isolated environments") if @config.allow_private_urls
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
def fetch(url, selector: nil, cookies: {}, headers: {}, &fallback)
|
|
29
|
+
UrlValidator.validate!(url, allow_private: @config.allow_private_urls)
|
|
30
|
+
|
|
31
|
+
context = { url: url, selector: selector, cookies: cookies, headers: headers }
|
|
32
|
+
run_middlewares(:before_request, url, context)
|
|
33
|
+
|
|
34
|
+
enforce_rate_limit
|
|
35
|
+
enforce_robots!(url)
|
|
36
|
+
|
|
37
|
+
html, mode = fetch_with_retry(url, selector, cookies, headers, &fallback)
|
|
38
|
+
result = Result.new(url, html, mode)
|
|
39
|
+
|
|
40
|
+
run_middlewares(:after_response, result, context)
|
|
41
|
+
result
|
|
42
|
+
rescue => e
|
|
43
|
+
run_middlewares(:on_error, e, context)
|
|
44
|
+
raise
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
def scrape(url, fields = {}, selector: nil, cookies: {}, headers: {}, &fallback)
|
|
48
|
+
fetch(url, selector: selector, cookies: cookies, headers: headers, &fallback).extract(fields)
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
def scrape_many(urls, fields = {}, selector: nil, cookies: {}, headers: {}, &fallback)
|
|
52
|
+
urls.map do |u|
|
|
53
|
+
scrape(u, fields, selector: selector, cookies: cookies, headers: headers, &fallback).merge("_url" => u)
|
|
54
|
+
end
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
def paginate(start_url, next_selector, limit: 10, fields: {}, selector: nil, cookies: {}, headers: {}, &fallback)
|
|
58
|
+
results = []
|
|
59
|
+
current = start_url
|
|
60
|
+
visited = []
|
|
61
|
+
|
|
62
|
+
limit.times do
|
|
63
|
+
break if current.nil? || visited.include?(current)
|
|
64
|
+
visited << current
|
|
65
|
+
|
|
66
|
+
result = fetch(current, selector: selector, cookies: cookies, headers: headers, &fallback)
|
|
67
|
+
results << (fields.empty? ? result : result.extract(fields).merge("_url" => current))
|
|
68
|
+
|
|
69
|
+
href = result.css(next_selector).first&.[]("href")
|
|
70
|
+
current = href ? URI.join(current, href).to_s : nil
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
results
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
def login(url, username:, password:, **opts)
|
|
77
|
+
@browser.login(url, username: username, password: password, **opts)
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
def export_csv(rows, path, headers: nil)
|
|
81
|
+
Exporter.to_csv(rows, path, headers: headers)
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
def export_json(rows, path, pretty: true)
|
|
85
|
+
Exporter.to_json(rows, path, pretty: pretty)
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
def shutdown
|
|
89
|
+
@browser.shutdown if @browser.respond_to?(:shutdown)
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
private
|
|
93
|
+
|
|
94
|
+
def run_middlewares(hook, *args)
|
|
95
|
+
(@config.middlewares || []).each do |mw|
|
|
96
|
+
next unless mw.respond_to?(hook)
|
|
97
|
+
mw.public_send(hook, *args)
|
|
98
|
+
rescue StandardError => e
|
|
99
|
+
Logger.warn(@config, "Middleware #{mw.class} failed on #{hook}: #{e.class}: #{e.message}")
|
|
100
|
+
end
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
private
|
|
104
|
+
|
|
105
|
+
def fetch_with_retry(url, selector, cookies, headers, &fallback)
|
|
106
|
+
attempts = 0
|
|
107
|
+
begin
|
|
108
|
+
attempts += 1
|
|
109
|
+
static_html = @static.fetch(url, cookies: cookies, headers: headers)
|
|
110
|
+
doc = Nokogiri::HTML(static_html)
|
|
111
|
+
|
|
112
|
+
needs_browser =
|
|
113
|
+
if block_given?
|
|
114
|
+
!fallback.call(doc)
|
|
115
|
+
elsif selector
|
|
116
|
+
doc.css(selector).empty?
|
|
117
|
+
else
|
|
118
|
+
false
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
if needs_browser
|
|
122
|
+
browser_html = @browser.fetch(url, cookies: cookies, headers: headers)
|
|
123
|
+
[browser_html, :browser]
|
|
124
|
+
else
|
|
125
|
+
[static_html, :static]
|
|
126
|
+
end
|
|
127
|
+
rescue LoadError
|
|
128
|
+
raise
|
|
129
|
+
rescue => e
|
|
130
|
+
if attempts <= @config.retries
|
|
131
|
+
delay = [@config.backoff_base * (2**(attempts - 1)), @config.backoff_max].min
|
|
132
|
+
delay += rand(0.0..0.25)
|
|
133
|
+
Logger.warn(@config, "Retry #{attempts}/#{@config.retries} for #{url} after #{delay.round(2)}s: #{e.class}")
|
|
134
|
+
sleep delay
|
|
135
|
+
retry
|
|
136
|
+
end
|
|
137
|
+
raise HybridScraper::Error, "Failed to fetch #{url}: #{e.class}: #{e.message}"
|
|
138
|
+
end
|
|
139
|
+
end
|
|
140
|
+
|
|
141
|
+
def enforce_rate_limit
|
|
142
|
+
@rate_mutex.synchronize do
|
|
143
|
+
delay = base_delay + jitter
|
|
144
|
+
if @last_request_at
|
|
145
|
+
elapsed = Time.now - @last_request_at
|
|
146
|
+
sleep(delay - elapsed) if elapsed < delay
|
|
147
|
+
end
|
|
148
|
+
@last_request_at = Time.now
|
|
149
|
+
end
|
|
150
|
+
end
|
|
151
|
+
|
|
152
|
+
def base_delay
|
|
153
|
+
@config.rate_limit.to_f
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
def jitter
|
|
157
|
+
min = @config.min_delay.to_f
|
|
158
|
+
max = @config.max_delay.to_f
|
|
159
|
+
return 0.0 if max <= min
|
|
160
|
+
rand(min..max)
|
|
161
|
+
end
|
|
162
|
+
|
|
163
|
+
def enforce_robots!(url)
|
|
164
|
+
return unless @config.respect_robots
|
|
165
|
+
unless Robots.allowed?(url, user_agent: @config.user_agent)
|
|
166
|
+
raise HybridScraper::Error, "Blocked by robots.txt: #{url}"
|
|
167
|
+
end
|
|
168
|
+
|
|
169
|
+
delay = Robots.crawl_delay(url, user_agent: @config.user_agent)
|
|
170
|
+
sleep(delay) if delay && delay.positive?
|
|
171
|
+
end
|
|
172
|
+
end
|
|
173
|
+
end
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
module HybridScraper
|
|
2
|
+
class Configuration
|
|
3
|
+
attr_accessor :user_agent, :timeout, :open_timeout, :retries,
|
|
4
|
+
:retry_delay, :rate_limit, :headless, :browser_options,
|
|
5
|
+
:proxy, :proxy_username, :proxy_password,
|
|
6
|
+
:cookies, :headers,
|
|
7
|
+
:user_agents, :rotate_user_agent,
|
|
8
|
+
:min_delay, :max_delay,
|
|
9
|
+
:stealth, :respect_robots,
|
|
10
|
+
:allow_private_urls,
|
|
11
|
+
:log_level, :backoff_base, :backoff_max,
|
|
12
|
+
:max_redirects, :reuse_browser,
|
|
13
|
+
:middlewares
|
|
14
|
+
|
|
15
|
+
def initialize
|
|
16
|
+
@user_agent = "HybridScraper/#{VERSION} (+https://github.com/yourname/hybrid_scraper)"
|
|
17
|
+
@timeout = 30
|
|
18
|
+
@open_timeout = 10
|
|
19
|
+
@retries = 3
|
|
20
|
+
@retry_delay = 1
|
|
21
|
+
@rate_limit = 0.0
|
|
22
|
+
@headless = true
|
|
23
|
+
@browser_options = {}
|
|
24
|
+
|
|
25
|
+
@proxy = nil
|
|
26
|
+
@proxy_username = nil
|
|
27
|
+
@proxy_password = nil
|
|
28
|
+
@cookies = {}
|
|
29
|
+
@headers = {}
|
|
30
|
+
|
|
31
|
+
@user_agents = []
|
|
32
|
+
@rotate_user_agent = false
|
|
33
|
+
@min_delay = 0.0
|
|
34
|
+
@max_delay = 0.0
|
|
35
|
+
@stealth = false
|
|
36
|
+
@respect_robots = false
|
|
37
|
+
@allow_private_urls = false
|
|
38
|
+
|
|
39
|
+
@log_level = :info
|
|
40
|
+
@backoff_base = 0.5
|
|
41
|
+
@backoff_max = 8.0
|
|
42
|
+
@max_redirects = 5
|
|
43
|
+
@reuse_browser = false
|
|
44
|
+
@middlewares = []
|
|
45
|
+
end
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
class << self
|
|
49
|
+
def configuration
|
|
50
|
+
@configuration ||= Configuration.new
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
def configure
|
|
54
|
+
yield configuration
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
def reset_configuration!
|
|
58
|
+
@configuration = Configuration.new
|
|
59
|
+
end
|
|
60
|
+
end
|
|
61
|
+
end
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
require "csv"
|
|
2
|
+
require "json"
|
|
3
|
+
|
|
4
|
+
module HybridScraper
|
|
5
|
+
module Exporter
|
|
6
|
+
def self.to_csv(rows, path, headers: nil)
|
|
7
|
+
rows = Array(rows)
|
|
8
|
+
headers ||= rows.first.is_a?(Hash) ? rows.first.keys : []
|
|
9
|
+
|
|
10
|
+
CSV.open(path, "w") do |csv|
|
|
11
|
+
csv << headers
|
|
12
|
+
rows.each do |row|
|
|
13
|
+
csv << headers.map do |h|
|
|
14
|
+
key = h.to_s
|
|
15
|
+
if row.is_a?(Hash)
|
|
16
|
+
row.key?(h) ? row[h] : row[key.to_sym]
|
|
17
|
+
elsif row.respond_to?(h)
|
|
18
|
+
row.public_send(h)
|
|
19
|
+
else
|
|
20
|
+
nil
|
|
21
|
+
end
|
|
22
|
+
rescue NoMethodError, TypeError
|
|
23
|
+
nil
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
end
|
|
27
|
+
path
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
def self.to_json(rows, path, pretty: true)
|
|
31
|
+
rows = Array(rows)
|
|
32
|
+
data = rows.map do |r|
|
|
33
|
+
if r.is_a?(Hash)
|
|
34
|
+
r
|
|
35
|
+
elsif r.respond_to?(:to_h)
|
|
36
|
+
r.to_h
|
|
37
|
+
else
|
|
38
|
+
r
|
|
39
|
+
end
|
|
40
|
+
rescue NoMethodError, TypeError
|
|
41
|
+
r
|
|
42
|
+
end
|
|
43
|
+
json = pretty ? JSON.pretty_generate(data) : data.to_json
|
|
44
|
+
File.write(path, json)
|
|
45
|
+
path
|
|
46
|
+
end
|
|
47
|
+
end
|
|
48
|
+
end
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
require "uri"
|
|
2
|
+
require "hybrid_scraper/user_agent"
|
|
3
|
+
require "hybrid_scraper/url_validator"
|
|
4
|
+
require "hybrid_scraper/logger"
|
|
5
|
+
|
|
6
|
+
module HybridScraper
|
|
7
|
+
module Fetchers
|
|
8
|
+
class BrowserFetcher
|
|
9
|
+
def initialize(config)
|
|
10
|
+
@config = config
|
|
11
|
+
@browser_mutex = Mutex.new
|
|
12
|
+
@browser_instance = nil
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
def fetch(url, cookies: {}, headers: {})
|
|
16
|
+
UrlValidator.validate!(url, allow_private: @config.allow_private_urls)
|
|
17
|
+
|
|
18
|
+
browser = acquire_browser
|
|
19
|
+
apply_stealth(browser)
|
|
20
|
+
apply_headers(browser, headers)
|
|
21
|
+
apply_cookies(browser, url, cookies)
|
|
22
|
+
|
|
23
|
+
browser.goto(url)
|
|
24
|
+
html = browser.body
|
|
25
|
+
|
|
26
|
+
release_browser(browser) unless @config.reuse_browser
|
|
27
|
+
html
|
|
28
|
+
rescue LoadError
|
|
29
|
+
raise HybridScraper::Error,
|
|
30
|
+
"Ferrum is not installed. Install it with: gem install ferrum"
|
|
31
|
+
rescue Ferrum::TimeoutError, Timeout::Error => e
|
|
32
|
+
handle_browser_failure(browser, e)
|
|
33
|
+
raise HybridScraper::TimeoutError, "Browser timeout for #{url}: #{e.message}"
|
|
34
|
+
rescue StandardError => e
|
|
35
|
+
handle_browser_failure(browser, e)
|
|
36
|
+
raise HybridScraper::BrowserError, "Browser error for #{url}: #{e.message}"
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
def login(url, username:, password:,
|
|
40
|
+
username_selector: "input[name='username'], input[name='email'], input[type='email']",
|
|
41
|
+
password_selector: "input[type='password']",
|
|
42
|
+
submit_selector: "button[type='submit'], input[type='submit']")
|
|
43
|
+
UrlValidator.validate!(url, allow_private: @config.allow_private_urls)
|
|
44
|
+
|
|
45
|
+
browser = acquire_browser
|
|
46
|
+
browser.goto(url)
|
|
47
|
+
|
|
48
|
+
user_el = browser.at_css(username_selector)
|
|
49
|
+
pass_el = browser.at_css(password_selector)
|
|
50
|
+
submit_el = browser.at_css(submit_selector)
|
|
51
|
+
|
|
52
|
+
raise HybridScraper::Error, "Login form not found" unless user_el && pass_el
|
|
53
|
+
|
|
54
|
+
user_el.focus
|
|
55
|
+
user_el.type(username)
|
|
56
|
+
pass_el.focus
|
|
57
|
+
pass_el.type(password)
|
|
58
|
+
submit_el&.click
|
|
59
|
+
|
|
60
|
+
sleep 1
|
|
61
|
+
{ url: browser.current_url, html: browser.body }
|
|
62
|
+
rescue StandardError => e
|
|
63
|
+
handle_browser_failure(browser, e)
|
|
64
|
+
raise HybridScraper::BrowserError, "Browser login failed: #{e.message}"
|
|
65
|
+
ensure
|
|
66
|
+
release_browser(browser) unless @config.reuse_browser
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
def shutdown
|
|
70
|
+
@browser_mutex.synchronize do
|
|
71
|
+
@browser_instance&.quit
|
|
72
|
+
@browser_instance = nil
|
|
73
|
+
end
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
private
|
|
77
|
+
|
|
78
|
+
def handle_browser_failure(browser, _error)
|
|
79
|
+
if @config.reuse_browser
|
|
80
|
+
# Drop the potentially broken instance so the next call recreates it.
|
|
81
|
+
@browser_mutex.synchronize do
|
|
82
|
+
browser&.quit
|
|
83
|
+
@browser_instance = nil if browser == @browser_instance
|
|
84
|
+
end
|
|
85
|
+
else
|
|
86
|
+
browser&.quit
|
|
87
|
+
end
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
def acquire_browser
|
|
91
|
+
if @config.reuse_browser
|
|
92
|
+
@browser_mutex.synchronize do
|
|
93
|
+
@browser_instance ||= new_browser
|
|
94
|
+
end
|
|
95
|
+
else
|
|
96
|
+
new_browser
|
|
97
|
+
end
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
def release_browser(browser)
|
|
101
|
+
browser&.quit unless @config.reuse_browser
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
def new_browser
|
|
105
|
+
proxy_hash = nil
|
|
106
|
+
if @config.proxy
|
|
107
|
+
uri = URI.parse(@config.proxy)
|
|
108
|
+
proxy_hash = { host: uri.host, port: uri.port }
|
|
109
|
+
proxy_hash[:user] = @config.proxy_username if @config.proxy_username
|
|
110
|
+
proxy_hash[:password] = @config.proxy_password if @config.proxy_password
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
bo = (@config.browser_options || {}).dup
|
|
114
|
+
bo["disable-extensions"] = nil unless bo.key?("disable-extensions")
|
|
115
|
+
bo["disable-file-system"] = nil unless bo.key?("disable-file-system")
|
|
116
|
+
bo["disable-dev-shm-usage"] = nil unless bo.key?("disable-dev-shm-usage")
|
|
117
|
+
|
|
118
|
+
if @config.stealth
|
|
119
|
+
bo["disable-blink-features"] = "AutomationControlled"
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
Ferrum::Browser.new(
|
|
123
|
+
headless: @config.headless,
|
|
124
|
+
timeout: @config.timeout,
|
|
125
|
+
proxy: proxy_hash,
|
|
126
|
+
browser_options: bo
|
|
127
|
+
)
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
def apply_stealth(browser)
|
|
131
|
+
return unless @config.stealth
|
|
132
|
+
browser.headers.set("User-Agent" => current_user_agent)
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
def apply_headers(browser, headers)
|
|
136
|
+
merged = (@config.headers || {}).merge(headers || {})
|
|
137
|
+
merged["User-Agent"] = current_user_agent unless merged.key?("User-Agent")
|
|
138
|
+
browser.headers.set(merged) unless merged.empty?
|
|
139
|
+
end
|
|
140
|
+
|
|
141
|
+
def apply_cookies(browser, url, cookies)
|
|
142
|
+
uri = URI.parse(url)
|
|
143
|
+
merged = {}
|
|
144
|
+
|
|
145
|
+
global = @config.cookies || {}
|
|
146
|
+
if global.values.all? { |v| v.is_a?(Hash) }
|
|
147
|
+
(global[uri.host] || global["*"] || {}).each { |k, v| merged[k] = v }
|
|
148
|
+
else
|
|
149
|
+
merged.merge!(global)
|
|
150
|
+
end
|
|
151
|
+
merged.merge!(cookies || {})
|
|
152
|
+
|
|
153
|
+
return if merged.empty?
|
|
154
|
+
|
|
155
|
+
merged.each do |name, value|
|
|
156
|
+
browser.cookies.set(name: name.to_s, value: value.to_s, domain: uri.host)
|
|
157
|
+
end
|
|
158
|
+
end
|
|
159
|
+
|
|
160
|
+
def current_user_agent
|
|
161
|
+
if @config.rotate_user_agent
|
|
162
|
+
UserAgent.pick(@config)
|
|
163
|
+
else
|
|
164
|
+
@config.user_agent
|
|
165
|
+
end
|
|
166
|
+
end
|
|
167
|
+
end
|
|
168
|
+
end
|
|
169
|
+
end
|