-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscraper.go
258 lines (210 loc) · 5.39 KB
/
scraper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
package goscrapeebay
import (
"bufio"
"errors"
"fmt"
"io"
"log/slog"
"net/url"
"os"
"strings"
"time"
)
var ErrContextTimeout = errors.New("context timeout")
type Config struct {
OutputFile string
TargetURL string
CategoriesFile string
MaxRetriesCategories int
MaxRetriesProducts int
MaxCategoriesPerPage int
MaxProductsPerPage int
SkipCategoryScraping bool
LogLevel string
CacheDir string
// Delay is the duration to wait before creating a new request to the matching domains
Delay time.Duration
// RandomDelay is the extra randomized duration to wait added to Delay before creating a new request
RandomDelay time.Duration
}
// LeveledLogger interface
type LeveledLogger interface {
Error(msg string, args ...any)
Info(msg string, args ...any)
Debug(msg string, args ...any)
Warn(msg string, args ...any)
}
// slogAdapter adapts slog.Logger to our LeveledLogger interface
type slogAdapter struct {
logger *slog.Logger
}
func (s *slogAdapter) Error(msg string, args ...any) {
s.logger.Error(msg, args...)
}
func (s *slogAdapter) Info(msg string, args ...any) {
s.logger.Info(msg, args...)
}
func (s *slogAdapter) Debug(msg string, args ...any) {
s.logger.Debug(msg, args...)
}
func (s *slogAdapter) Warn(msg string, args ...any) {
s.logger.Warn(msg, args...)
}
func createLogger(level string) (LeveledLogger, error) {
var logLevel slog.Level
switch level {
case "DEBUG":
logLevel = slog.LevelDebug
case "INFO":
logLevel = slog.LevelInfo
case "WARN":
logLevel = slog.LevelWarn
case "ERROR":
logLevel = slog.LevelError
default:
return nil, fmt.Errorf("invalid log level: %s", level)
}
opts := &slog.HandlerOptions{
Level: logLevel,
}
handler := slog.NewJSONHandler(os.Stderr, opts)
logger := slog.New(handler)
return &slogAdapter{logger: logger}, nil
}
type EbayScraper struct {
config Config
logger LeveledLogger
}
func NewEbayScraper(cfg Config) (*EbayScraper, error) {
logger, err := createLogger(cfg.LogLevel)
if err != nil {
return nil, fmt.Errorf("error creating logger: %w", err)
}
return &EbayScraper{
config: cfg,
logger: logger,
}, nil
}
func (s *EbayScraper) Run() error {
if !s.config.SkipCategoryScraping {
if err := s.runCategoryScrape(); err != nil {
return err
}
}
return s.runProductsScrape()
}
func (s *EbayScraper) runCategoryScrape() error {
rootCategoryURL, err := url.Parse(s.config.TargetURL)
if err != nil {
return fmt.Errorf("error parsing URL: %w", err)
}
file, err := os.Create(s.config.CategoriesFile)
if err != nil {
return fmt.Errorf("error creating output file: %w", err)
}
defer file.Close()
w := bufio.NewWriter(file)
defer w.Flush()
// Retry loop
var lastErr error
for i := 0; i < s.config.MaxRetriesCategories; i++ {
err = s.scrapeLeafCateories(rootCategoryURL, w)
if err == nil {
s.logger.Info("Scraping succeeded")
break
}
if errors.Is(err, ErrContextTimeout) {
s.logger.Warn("Context timeout, retrying", "attempt", i+1)
} else {
s.logger.Error("Scraping error", "error", err)
break
}
lastErr = err
}
if lastErr != nil {
s.logger.Error("Failed to collect categories after maximum attempts",
"max_attempts", s.config.MaxRetriesCategories,
"error", lastErr)
}
return nil
}
func (s *EbayScraper) runProductsScrape() error {
s.logger.Info("Started scraping product details pages")
outputFile, err := os.Create(s.config.OutputFile)
if err != nil {
return fmt.Errorf("error creating output file: %w", err)
}
defer outputFile.Close()
w := bufio.NewWriter(outputFile)
defer w.Flush()
categoriesFile, err := os.Open(s.config.CategoriesFile)
if err != nil {
return fmt.Errorf("error opening urls file: %w", err)
}
defer categoriesFile.Close()
var (
line []byte
readErr error
lastErr error
pos int64
)
lineNum := 1
for i := 0; i < s.config.MaxRetriesProducts; i++ {
if _, err := categoriesFile.Seek(pos, io.SeekStart); err != nil {
return err
}
r := bufio.NewReader(categoriesFile)
var errChan chan error
c := s.setupProductDetailsCollector(w, errChan)
for {
errChan = make(chan error, 1)
line, readErr = r.ReadBytes('\n')
fmt.Printf("[line:%d pos:%d] %q\n", lineNum, pos, line)
if readErr != nil {
break
}
pos += int64(len(line))
lineNum++
leafURL := strings.Split(string(line), "\n")[0]
u, err := url.Parse(leafURL)
if err != nil {
s.logger.Error("URL parsing error", "error", err, "category", leafURL)
continue
}
go func() {
err := c.Visit(u.String())
s.logger.Error("Visiting Err", "err", err)
if err != nil {
select {
case errChan <- err:
default:
// no op
}
}
close(errChan)
}()
err = <-errChan
if err == nil {
s.logger.Info("Details page scraped", "url", u.String())
continue
}
if errors.Is(err, ErrContextTimeout) {
s.logger.Warn("Context timeout, retrying", "attempt", i+1)
break
} else {
s.logger.Error("Failed to scrape product details page", "error", err, "category", leafURL)
}
lastErr = err
}
if readErr != nil && readErr != io.EOF {
s.logger.Error("Failed to read file", "err", readErr.Error())
return err
}
}
if lastErr != nil {
s.logger.Error("Failed to scraped products after maximum attempts",
"max_attempts", s.config.MaxRetriesProducts,
"error", lastErr)
}
return nil
}