-
-
Notifications
You must be signed in to change notification settings - Fork 34
/
cdpfn.go
380 lines (364 loc) · 9.5 KB
/
cdpfn.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
package runn
import (
"context"
"fmt"
"os"
"path/filepath"
"time"
"github.com/chromedp/cdproto/domstorage"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
"github.com/k1LoW/duration"
)
type CDPArgType string
const (
CDPArgTypeArg CDPArgType = "arg"
CDPArgTypeRes CDPArgType = "res"
)
type CDPFnArg struct {
Typ CDPArgType
Key string
Example string
}
type CDPFnArgs []CDPFnArg
type CDPFn struct {
Desc string
Fn any
Args CDPFnArgs
Aliases []string
}
var CDPFnMap = map[string]CDPFn{
"navigate": {
Desc: "Navigate the current frame to `url` page.",
Fn: chromedp.Navigate,
Args: CDPFnArgs{
{CDPArgTypeArg, "url", "https://pkg.go.dev/time"},
},
},
"latestTab": {
Desc: "Change current frame to latest tab.",
Fn: func() chromedp.Action {
// dummy
return nil
},
Args: CDPFnArgs{},
Aliases: []string{"latestTarget"},
},
"click": {
Desc: "Send a mouse click event to the first element node matching the selector (`sel`).",
Fn: chromedp.Click,
Args: CDPFnArgs{
{CDPArgTypeArg, "sel", "nav > div > a"},
},
},
"doubleClick": {
Desc: "Send a mouse double click event to the first element node matching the selector (`sel`).",
Fn: chromedp.DoubleClick,
Args: CDPFnArgs{
{CDPArgTypeArg, "sel", "nav > div > li"},
},
},
"sendKeys": {
Desc: "Send keys (`value`) to the first element node matching the selector (`sel`).",
Fn: chromedp.SendKeys,
Args: CDPFnArgs{
{CDPArgTypeArg, "sel", "input[name=username]"},
{CDPArgTypeArg, "value", "[email protected]"},
},
},
"submit": {
Desc: "Submit the parent form of the first element node matching the selector (`sel`).",
Fn: chromedp.Submit,
Args: CDPFnArgs{
{CDPArgTypeArg, "sel", "form.login"},
},
},
"scroll": {
Desc: "Scroll the window to the first element node matching the selector (`sel`).",
Fn: chromedp.ScrollIntoView,
Args: CDPFnArgs{
{CDPArgTypeArg, "sel", "body > footer"},
},
Aliases: []string{"scrollIntoView"},
},
"wait": {
Desc: "Wait for the specified `time`.",
Fn: func(d string) chromedp.Action {
return &waitAction{d: d}
},
Args: CDPFnArgs{
{CDPArgTypeArg, "time", "10sec"},
},
Aliases: []string{"sleep"},
},
"waitReady": {
Desc: "Wait until the element matching the selector (`sel`) is ready.",
Fn: chromedp.WaitReady,
Args: CDPFnArgs{
{CDPArgTypeArg, "sel", "body > footer"},
},
},
"waitVisible": {
Desc: "Wait until the element matching the selector (`sel`) is visible.",
Fn: chromedp.WaitVisible,
Args: CDPFnArgs{
{CDPArgTypeArg, "sel", "body > footer"},
},
},
"setUserAgent": {
Desc: "Set the default User-Agent",
Fn: func(ua string) []chromedp.Action {
headers := map[string]any{"User-Agent": ua}
return []chromedp.Action{
network.Enable(),
network.SetExtraHTTPHeaders(network.Headers(headers)),
}
},
Args: CDPFnArgs{
{CDPArgTypeArg, "userAgent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"},
},
Aliases: []string{"setUA", "ua", "userAgent"},
},
"text": {
Desc: "Get the visible text of the first element node matching the selector (`sel`).",
Fn: chromedp.Text,
Args: CDPFnArgs{
{CDPArgTypeArg, "sel", "h1"},
{CDPArgTypeRes, "text", "Install the latest version of Go"},
},
Aliases: []string{"getText"},
},
"textContent": {
Desc: "Get the text content of the first element node matching the selector (`sel`).",
Fn: chromedp.TextContent,
Args: CDPFnArgs{
{CDPArgTypeArg, "sel", "h1"},
{CDPArgTypeRes, "text", "Install the latest version of Go"},
},
Aliases: []string{"getTextContent"},
},
"innerHTML": {
Desc: "Get the inner html of the first element node matching the selector (`sel`).",
Fn: chromedp.InnerHTML,
Args: CDPFnArgs{
{CDPArgTypeArg, "sel", "h1"},
{CDPArgTypeRes, "html", "Install the latest version of Go"},
},
Aliases: []string{"getInnerHTML"},
},
"outerHTML": {
Desc: "Get the outer html of the first element node matching the selector (`sel`).",
Fn: chromedp.OuterHTML,
Args: CDPFnArgs{
{CDPArgTypeArg, "sel", "h1"},
{CDPArgTypeRes, "html", "<h1>Install the latest version of Go</h1>"},
},
Aliases: []string{"getOuterHTML"},
},
"fullHTML": {
Desc: "Get the full html of page.",
Fn: func(html *string) chromedp.Action {
expr := "new XMLSerializer().serializeToString(document);"
return chromedp.Evaluate(expr, html)
},
Args: CDPFnArgs{
{CDPArgTypeRes, "html", "<!DOCTYPE html><html><body><h1>hello</h1></body></html>"},
},
Aliases: []string{"getFullHTML", "getHTML", "html"},
},
"value": {
Desc: "Get the Javascript value field of the first element node matching the selector (`sel`).",
Fn: chromedp.Value,
Args: CDPFnArgs{
{CDPArgTypeArg, "sel", "input[name=address]"},
{CDPArgTypeRes, "value", "Fukuoka"},
},
Aliases: []string{"getValue"},
},
"setUploadFile": {
Desc: "Set upload file (`path`) to the first element node matching the selector (`sel`).",
Fn: func(sel, path string) chromedp.Action {
abs, err := filepath.Abs(path)
if err != nil {
return &errAction{err: err}
}
if _, err := os.Stat(abs); err != nil {
return &errAction{err: err}
}
return chromedp.SetUploadFiles(sel, []string{abs})
},
Args: CDPFnArgs{
{CDPArgTypeArg, "sel", "input[name=avator]"},
{CDPArgTypeArg, "path", "/path/to/image.png"},
},
Aliases: []string{"setUpload"},
},
"title": {
Desc: "Get the document `title`.",
Fn: chromedp.Title,
Args: CDPFnArgs{
{CDPArgTypeRes, "title", "GitHub"},
},
Aliases: []string{"getTitle"},
},
"location": {
Desc: "Get the document location.",
Fn: chromedp.Location,
Args: CDPFnArgs{
{CDPArgTypeRes, "url", "https://github.com"},
},
Aliases: []string{"getLocation"},
},
"attributes": {
Desc: "Get the element attributes for the first element node matching the selector (`sel`).",
Fn: chromedp.Attributes,
Args: CDPFnArgs{
{CDPArgTypeArg, "sel", "h1"},
{CDPArgTypeRes, "attrs", `{"class": "sr-only"}`},
},
Aliases: []string{"getAttributes", "attrs", "getAttrs"},
},
"screenshot": {
Desc: "Take a full screenshot of the entire browser viewport.",
Fn: func(b *[]byte) chromedp.Action {
return chromedp.FullScreenshot(b, 100)
},
Args: CDPFnArgs{
{CDPArgTypeRes, "png", "[]byte"},
},
Aliases: []string{"getScreenshot"},
},
"evaluate": {
Desc: "Evaluate the Javascript expression (`expr`).",
Fn: func(expr string) chromedp.Action {
// ignore the return value of 'evaluate'
return chromedp.Evaluate(expr, nil)
},
Args: CDPFnArgs{
{CDPArgTypeArg, "expr", `document.querySelector("h1").textContent = "hello"`},
},
Aliases: []string{"eval"},
},
"localStorage": {
Desc: "Get localStorage items.",
Fn: func(origin string, items *map[string]string) chromedp.Action {
return chromedp.ActionFunc(func(ctx context.Context) error {
frameTree, err := page.GetFrameTree().Do(ctx)
if err != nil {
return err
}
strageKey := domstorage.SerializedStorageKey(frameTree.Frame.SecurityOrigin + "/")
storageID := &domstorage.StorageID{
StorageKey: strageKey,
IsLocalStorage: true,
}
resp, err := domstorage.GetDOMStorageItems(storageID).Do(ctx)
if err != nil {
return err
}
m := make(map[string]string)
for _, v := range resp {
if len(v) != 2 {
continue
}
m[v[0]] = v[1]
}
*items = m
return nil
})
},
Args: CDPFnArgs{
{CDPArgTypeArg, "origin", "https://github.com"},
{CDPArgTypeRes, "items", `{"key": "value"}`},
},
Aliases: []string{"getLocalStorage"},
},
"sessionStorage": {
Desc: "Get sessionStorage items.",
Fn: func(origin string, items *map[string]string) chromedp.Action {
return chromedp.ActionFunc(func(ctx context.Context) error {
frameTree, err := page.GetFrameTree().Do(ctx)
if err != nil {
return err
}
strageKey := domstorage.SerializedStorageKey(frameTree.Frame.SecurityOrigin + "/")
storageID := &domstorage.StorageID{
StorageKey: strageKey,
IsLocalStorage: false,
}
resp, err := domstorage.GetDOMStorageItems(storageID).Do(ctx)
if err != nil {
return err
}
m := make(map[string]string)
for _, v := range resp {
if len(v) != 2 {
continue
}
m[v[0]] = v[1]
}
*items = m
return nil
})
},
Args: CDPFnArgs{
{CDPArgTypeArg, "origin", "https://github.com"},
{CDPArgTypeRes, "items", `{"key": "value"}`},
},
Aliases: []string{"getSessionStorage"},
},
}
func findCDPFn(k string) (string, CDPFn, error) {
fn, ok := CDPFnMap[k]
if ok {
return k, fn, nil
}
for kk, fn := range CDPFnMap {
for _, a := range fn.Aliases {
if a == k {
return kk, fn, nil
}
}
}
return "", CDPFn{}, fmt.Errorf("not found function: %s", k)
}
func (a CDPFnArgs) ArgArgs() CDPFnArgs { //nostyle:recvtype
res := CDPFnArgs{}
for _, arg := range a {
if arg.Typ == CDPArgTypeArg {
res = append(res, arg)
}
}
return res
}
func (a CDPFnArgs) ResArgs() CDPFnArgs { //nostyle:recvtype
res := CDPFnArgs{}
for _, arg := range a {
if arg.Typ == CDPArgTypeRes {
res = append(res, arg)
}
}
return res
}
var (
_ chromedp.Action = (*waitAction)(nil)
_ chromedp.Action = (*errAction)(nil)
)
type waitAction struct {
d string
}
func (w *waitAction) Do(ctx context.Context) error {
d, err := duration.Parse(w.d)
if err != nil {
return err
}
time.Sleep(d)
return nil
}
type errAction struct {
err error
}
func (e *errAction) Do(ctx context.Context) error {
return e.err
}