forked from gosom/google-maps-scraper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
286 lines (225 loc) · 6.53 KB
/
main.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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
package main
import (
"bufio"
"context"
"database/sql"
"encoding/csv"
"flag"
"io"
"os"
"runtime"
"strings"
"time"
// postgres driver
_ "github.com/jackc/pgx/v5/stdlib"
"github.com/gosom/scrapemate"
"github.com/gosom/scrapemate/adapters/writers/csvwriter"
"github.com/gosom/scrapemate/adapters/writers/jsonwriter"
"github.com/gosom/scrapemate/scrapemateapp"
"github.com/playwright-community/playwright-go"
"github.com/gosom/google-maps-scraper/gmaps"
"github.com/gosom/google-maps-scraper/postgres"
)
func main() {
// just install playwright
if os.Getenv("PLAYWRIGHT_INSTALL_ONLY") == "1" {
if err := installPlaywright(); err != nil {
os.Exit(1)
}
os.Exit(0)
}
if err := run(); err != nil {
os.Stderr.WriteString(err.Error() + "\n")
os.Exit(1)
return
}
os.Exit(0)
}
func run() error {
ctx := context.Background()
args := parseArgs()
if args.dsn == "" {
return runFromLocalFile(ctx, &args)
}
return runFromDatabase(ctx, &args)
}
func runFromLocalFile(ctx context.Context, args *arguments) error {
var input io.Reader
switch args.inputFile {
case "stdin":
input = os.Stdin
default:
f, err := os.Open(args.inputFile)
if err != nil {
return err
}
defer f.Close()
input = f
}
var resultsWriter io.Writer
switch args.resultsFile {
case "stdout":
resultsWriter = os.Stdout
default:
f, err := os.Create(args.resultsFile)
if err != nil {
return err
}
defer f.Close()
resultsWriter = f
}
csvWriter := csvwriter.NewCsvWriter(csv.NewWriter(resultsWriter))
writers := []scrapemate.ResultWriter{}
if args.json {
writers = append(writers, jsonwriter.NewJSONWriter(resultsWriter))
} else {
writers = append(writers, csvWriter)
}
opts := []func(*scrapemateapp.Config) error{
// scrapemateapp.WithCache("leveldb", "cache"),
scrapemateapp.WithConcurrency(args.concurrency),
scrapemateapp.WithExitOnInactivity(args.exitOnInactivityDuration),
}
if args.debug {
opts = append(opts, scrapemateapp.WithJS(scrapemateapp.Headfull()))
} else {
opts = append(opts, scrapemateapp.WithJS())
}
cfg, err := scrapemateapp.NewConfig(
writers,
opts...,
)
if err != nil {
return err
}
app, err := scrapemateapp.NewScrapeMateApp(cfg)
if err != nil {
return err
}
seedJobs, err := createSeedJobs(args.langCode, input, args.maxDepth, args.email)
if err != nil {
return err
}
return app.Start(ctx, seedJobs...)
}
func runFromDatabase(ctx context.Context, args *arguments) error {
db, err := openPsqlConn(args.dsn)
if err != nil {
return err
}
provider := postgres.NewProvider(db)
if args.produceOnly {
return produceSeedJobs(ctx, args, provider)
}
psqlWriter := postgres.NewResultWriter(db)
writers := []scrapemate.ResultWriter{
psqlWriter,
}
opts := []func(*scrapemateapp.Config) error{
// scrapemateapp.WithCache("leveldb", "cache"),
scrapemateapp.WithConcurrency(args.concurrency),
scrapemateapp.WithProvider(provider),
scrapemateapp.WithExitOnInactivity(args.exitOnInactivityDuration),
}
if args.debug {
opts = append(opts, scrapemateapp.WithJS(scrapemateapp.Headfull()))
} else {
opts = append(opts, scrapemateapp.WithJS())
}
cfg, err := scrapemateapp.NewConfig(
writers,
opts...,
)
if err != nil {
return err
}
app, err := scrapemateapp.NewScrapeMateApp(cfg)
if err != nil {
return err
}
return app.Start(ctx)
}
func produceSeedJobs(ctx context.Context, args *arguments, provider scrapemate.JobProvider) error {
var input io.Reader
switch args.inputFile {
case "stdin":
input = os.Stdin
default:
f, err := os.Open(args.inputFile)
if err != nil {
return err
}
defer f.Close()
input = f
}
jobs, err := createSeedJobs(args.langCode, input, args.maxDepth, args.email)
if err != nil {
return err
}
for i := range jobs {
if err := provider.Push(ctx, jobs[i]); err != nil {
return err
}
}
return nil
}
func createSeedJobs(langCode string, r io.Reader, maxDepth int, email bool) (jobs []scrapemate.IJob, err error) {
scanner := bufio.NewScanner(r)
for scanner.Scan() {
query := strings.TrimSpace(scanner.Text())
if query == "" {
continue
}
jobs = append(jobs, gmaps.NewGmapJob(langCode, query, maxDepth, email))
}
return jobs, scanner.Err()
}
func installPlaywright() error {
return playwright.Install()
}
type arguments struct {
concurrency int
cacheDir string
maxDepth int
inputFile string
resultsFile string
json bool
langCode string
debug bool
dsn string
produceOnly bool
exitOnInactivityDuration time.Duration
email bool
}
func parseArgs() (args arguments) {
const (
defaultDepth = 10
defaultCPUDivider = 2
)
defaultConcurency := runtime.NumCPU() / defaultCPUDivider
if defaultConcurency < 1 {
defaultConcurency = 1
}
flag.IntVar(&args.concurrency, "c", defaultConcurency, "sets the concurrency. By default it is set to half of the number of CPUs")
flag.StringVar(&args.cacheDir, "cache", "cache", "sets the cache directory (no effect at the moment)")
flag.IntVar(&args.maxDepth, "depth", defaultDepth, "is how much you allow the scraper to scroll in the search results. Experiment with that value")
flag.StringVar(&args.resultsFile, "results", "stdout", "is the path to the file where the results will be written")
flag.StringVar(&args.inputFile, "input", "stdin", "is the path to the file where the queries are stored (one query per line). By default it reads from stdin")
flag.StringVar(&args.langCode, "lang", "en", "is the languate code to use for google (the hl urlparam).Default is en . For example use de for German or el for Greek")
flag.BoolVar(&args.debug, "debug", false, "Use this to perform a headfull crawl (it will open a browser window) [only when using without docker]")
flag.StringVar(&args.dsn, "dsn", "", "Use this if you want to use a database provider")
flag.BoolVar(&args.produceOnly, "produce", false, "produce seed jobs only (only valid with dsn)")
flag.DurationVar(&args.exitOnInactivityDuration, "exit-on-inactivity", 0, "program exits after this duration of inactivity(example value '5m')")
flag.BoolVar(&args.json, "json", false, "Use this to produce a json file instead of csv (not available when using db)")
flag.BoolVar(&args.email, "email", false, "Use this to extract emails from the websites")
flag.Parse()
return args
}
func openPsqlConn(dsn string) (conn *sql.DB, err error) {
conn, err = sql.Open("pgx", dsn)
if err != nil {
return
}
err = conn.Ping()
return
}