forked from chromedp/chromedp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
750 lines (648 loc) · 17.6 KB
/
example_test.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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
package chromedp_test
import (
"bytes"
"context"
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"time"
"github.com/chromedp/chromedp"
"github.com/chromedp/chromedp/device"
"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/dom"
"github.com/chromedp/cdproto/page"
"github.com/chromedp/cdproto/runtime"
"github.com/chromedp/cdproto/target"
)
func writeHTML(content string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
io.WriteString(w, strings.TrimSpace(content))
})
}
func ExampleTitle() {
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
ts := httptest.NewServer(writeHTML(`
<head>
<title>fancy website title</title>
</head>
<body>
<div id="content"></div>
</body>
`))
defer ts.Close()
var title string
if err := chromedp.Run(ctx,
chromedp.Navigate(ts.URL),
chromedp.Title(&title),
); err != nil {
log.Fatal(err)
}
fmt.Println(title)
// Output:
// fancy website title
}
func ExampleRunResponse() {
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
// This server simply shows the URL path as the page title, and contains
// a link that points to /foo.
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
fmt.Fprintf(w, `
<head><title>%s</title></head>
<body><a id="foo" href="/foo">foo</a></body>
`, r.URL.Path)
}))
defer ts.Close()
// The Navigate action already waits until a page loads, so Title runs
// once the page is ready.
var firstTitle string
if err := chromedp.Run(ctx,
chromedp.Navigate(ts.URL),
chromedp.Title(&firstTitle),
); err != nil {
log.Fatal(err)
}
fmt.Println("first title:", firstTitle)
// However, actions like Click don't always trigger a page navigation,
// so they don't wait for a page load directly. Wrapping them with
// RunResponse does that waiting, and also obtains the HTTP response.
resp, err := chromedp.RunResponse(ctx, chromedp.Click("#foo", chromedp.ByID))
if err != nil {
log.Fatal(err)
}
fmt.Println("second status code:", resp.Status)
// Grabbing the title again should work, as the page has finished
// loading once more.
var secondTitle string
if err := chromedp.Run(ctx, chromedp.Title(&secondTitle)); err != nil {
log.Fatal(err)
}
fmt.Println("second title:", secondTitle)
// Finally, it's always possible to wrap Navigate with RunResponse, if
// one wants the response information for that case too.
resp, err = chromedp.RunResponse(ctx, chromedp.Navigate(ts.URL+"/bar"))
if err != nil {
log.Fatal(err)
}
fmt.Println("third status code:", resp.Status)
// Output:
// first title: /
// second status code: 200
// second title: /foo
// third status code: 200
}
func ExampleExecAllocator() {
dir, err := os.MkdirTemp("", "chromedp-example")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
opts := append(chromedp.DefaultExecAllocatorOptions[:],
chromedp.DisableGPU,
chromedp.UserDataDir(dir),
)
allocCtx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
defer cancel()
// also set up a custom logger
taskCtx, cancel := chromedp.NewContext(allocCtx, chromedp.WithLogf(log.Printf))
defer cancel()
// ensure that the browser process is started
if err := chromedp.Run(taskCtx); err != nil {
log.Fatal(err)
}
path := filepath.Join(dir, "DevToolsActivePort")
bs, err := os.ReadFile(path)
if err != nil {
log.Fatal(err)
}
lines := bytes.Split(bs, []byte("\n"))
fmt.Printf("DevToolsActivePort has %d lines\n", len(lines))
// Output:
// DevToolsActivePort has 2 lines
}
func ExampleNewContext_reuseBrowser() {
ts := httptest.NewServer(writeHTML(`
<body>
<script>
// Show the current cookies.
var p = document.createElement("p")
p.innerText = document.cookie
p.setAttribute("id", "cookies")
document.body.appendChild(p)
// Override the cookies.
document.cookie = "foo=bar"
</script>
</body>
`))
defer ts.Close()
// create a new browser
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
// start the browser without a timeout
if err := chromedp.Run(ctx); err != nil {
log.Fatal(err)
}
for i := 0; i < 2; i++ {
func() {
ctx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
ctx, cancel = chromedp.NewContext(ctx)
defer cancel()
var cookies string
if err := chromedp.Run(ctx,
chromedp.Navigate(ts.URL),
chromedp.Text("#cookies", &cookies),
); err != nil {
log.Fatal(err)
}
fmt.Printf("Cookies at i=%d: %q\n", i, cookies)
}()
}
// Output:
// Cookies at i=0: ""
// Cookies at i=1: "foo=bar"
}
func ExampleNewContext_manyTabs() {
// new browser, first tab
ctx1, cancel := chromedp.NewContext(context.Background())
defer cancel()
// ensure the first tab is created
if err := chromedp.Run(ctx1); err != nil {
log.Fatal(err)
}
// same browser, second tab
ctx2, _ := chromedp.NewContext(ctx1)
// ensure the second tab is created
if err := chromedp.Run(ctx2); err != nil {
log.Fatal(err)
}
c1 := chromedp.FromContext(ctx1)
c2 := chromedp.FromContext(ctx2)
fmt.Printf("Same browser: %t\n", c1.Browser == c2.Browser)
fmt.Printf("Same tab: %t\n", c1.Target == c2.Target)
// Output:
// Same browser: true
// Same tab: false
}
func ExampleListenTarget_consoleLog() {
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
ts := httptest.NewServer(writeHTML(`
<body>
<script>
console.log("hello js world")
console.warn("scary warning", 123)
null.throwsException
</script>
</body>
`))
defer ts.Close()
gotException := make(chan bool, 1)
chromedp.ListenTarget(ctx, func(ev interface{}) {
switch ev := ev.(type) {
case *runtime.EventConsoleAPICalled:
fmt.Printf("* console.%s call:\n", ev.Type)
for _, arg := range ev.Args {
fmt.Printf("%s - %s\n", arg.Type, arg.Value)
}
case *runtime.EventExceptionThrown:
// Since ts.URL uses a random port, replace it.
s := ev.ExceptionDetails.Error()
s = strings.ReplaceAll(s, ts.URL, "<server>")
// V8 has changed the error messages for property access on null/undefined in version 9.3.310.
// see: https://chromium.googlesource.com/v8/v8/+/c0fd89c3c089e888c4f4e8582e56db7066fa779b
// https://github.com/chromium/chromium/commit/1735cbf94c98c70ff7554a1e9e01bb9a4f91beb6
// The message is normalized to make it compatible with the versions before this change.
s = strings.ReplaceAll(s, "Cannot read property 'throwsException' of null", "Cannot read properties of null (reading 'throwsException')")
fmt.Printf("* %s\n", s)
gotException <- true
}
})
if err := chromedp.Run(ctx, chromedp.Navigate(ts.URL)); err != nil {
log.Fatal(err)
}
<-gotException
// Output:
// * console.log call:
// string - "hello js world"
// * console.warning call:
// string - "scary warning"
// number - 123
// * exception "Uncaught" (4:6): TypeError: Cannot read properties of null (reading 'throwsException')
// at <server>/:5:7
}
func ExampleWaitNewTarget() {
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
mux := http.NewServeMux()
mux.Handle("/first", writeHTML(`
<input id='newtab' type='button' value='open' onclick='window.open("/second", "_blank");'/>
`))
mux.Handle("/second", writeHTML(``))
ts := httptest.NewServer(mux)
defer ts.Close()
// Grab the first spawned tab that isn't blank.
ch := chromedp.WaitNewTarget(ctx, func(info *target.Info) bool {
return info.URL != ""
})
if err := chromedp.Run(ctx,
chromedp.Navigate(ts.URL+"/first"),
chromedp.Click("#newtab", chromedp.ByID),
); err != nil {
log.Fatal(err)
}
newCtx, cancel := chromedp.NewContext(ctx, chromedp.WithTargetID(<-ch))
defer cancel()
var urlstr string
if err := chromedp.Run(newCtx, chromedp.Location(&urlstr)); err != nil {
log.Fatal(err)
}
fmt.Println("new tab's path:", strings.TrimPrefix(urlstr, ts.URL))
// Output:
// new tab's path: /second
}
func ExampleListenTarget_acceptAlert() {
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
mux := http.NewServeMux()
mux.Handle("/second", writeHTML(``))
ts := httptest.NewServer(writeHTML(`
<input id='alert' type='button' value='alert' onclick='alert("alert text");'/>
`))
defer ts.Close()
chromedp.ListenTarget(ctx, func(ev interface{}) {
if ev, ok := ev.(*page.EventJavascriptDialogOpening); ok {
fmt.Println("closing alert:", ev.Message)
go func() {
if err := chromedp.Run(ctx,
page.HandleJavaScriptDialog(true),
); err != nil {
log.Fatal(err)
}
}()
}
})
if err := chromedp.Run(ctx,
chromedp.Navigate(ts.URL),
chromedp.Click("#alert", chromedp.ByID),
); err != nil {
log.Fatal(err)
}
// Output:
// closing alert: alert text
}
func Example_retrieveHTML() {
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
ts := httptest.NewServer(writeHTML(`
<body>
<p id="content" onclick="changeText()">Original content.</p>
<script>
function changeText() {
document.getElementById("content").textContent = "New content!"
}
</script>
</body>
`))
defer ts.Close()
var outerBefore, outerAfter string
if err := chromedp.Run(ctx,
chromedp.Navigate(ts.URL),
chromedp.OuterHTML("#content", &outerBefore, chromedp.ByQuery),
chromedp.Click("#content", chromedp.ByQuery),
chromedp.OuterHTML("#content", &outerAfter, chromedp.ByQuery),
); err != nil {
log.Fatal(err)
}
fmt.Println("OuterHTML before clicking:")
fmt.Println(outerBefore)
fmt.Println("OuterHTML after clicking:")
fmt.Println(outerAfter)
// Output:
// OuterHTML before clicking:
// <p id="content" onclick="changeText()">Original content.</p>
// OuterHTML after clicking:
// <p id="content" onclick="changeText()">New content!</p>
}
func ExampleEmulate() {
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
var buf []byte
if err := chromedp.Run(ctx,
chromedp.Emulate(device.IPhone7),
chromedp.Navigate(`https://duckduckgo.com/`),
chromedp.SendKeys(`input[name=q]`, "what's my user agent?\n"),
chromedp.WaitVisible(`#zci-answer`, chromedp.ByID),
chromedp.CaptureScreenshot(&buf),
); err != nil {
log.Fatal(err)
}
if err := os.WriteFile("iphone7-ua.png", buf, 0o644); err != nil {
log.Fatal(err)
}
// Output:
}
func ExamplePrintToPDF() {
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
var buf []byte
if err := chromedp.Run(ctx,
chromedp.Navigate(`https://pkg.go.dev/github.com/chromedp/chromedp`),
chromedp.ActionFunc(func(ctx context.Context) error {
var err error
buf, _, err = page.PrintToPDF().
WithDisplayHeaderFooter(false).
WithLandscape(true).
Do(ctx)
return err
}),
); err != nil {
log.Fatal(err)
}
if err := os.WriteFile("page.pdf", buf, 0o644); err != nil {
log.Fatal(err)
}
// Output:
}
func ExampleByJSPath() {
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
ts := httptest.NewServer(writeHTML(`
<body>
<div id="content">cool content</div>
</body>
`))
defer ts.Close()
var ids []cdp.NodeID
var html string
if err := chromedp.Run(ctx,
chromedp.Navigate(ts.URL),
chromedp.NodeIDs(`document`, &ids, chromedp.ByJSPath),
chromedp.ActionFunc(func(ctx context.Context) error {
var err error
html, err = dom.GetOuterHTML().WithNodeID(ids[0]).Do(ctx)
return err
}),
); err != nil {
log.Fatal(err)
}
fmt.Println("Outer HTML:")
fmt.Println(html)
// Output:
// Outer HTML:
// <html><head></head><body>
// <div id="content">cool content</div>
// </body></html>
}
func ExampleFromNode() {
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
ts := httptest.NewServer(writeHTML(`
<body>
<p class="content">outer content</p>
<div id="section"><p class="content">inner content</p></div>
</body>
`))
defer ts.Close()
var nodes []*cdp.Node
if err := chromedp.Run(ctx,
chromedp.Navigate(ts.URL),
chromedp.Nodes("#section", &nodes, chromedp.ByQuery),
); err != nil {
log.Fatal(err)
}
sectionNode := nodes[0]
var queryRoot, queryFromNode, queryNestedSelector string
if err := chromedp.Run(ctx,
// Queries run from the document root by default, so Text will
// pick the first node it finds.
chromedp.Text(".content", &queryRoot, chromedp.ByQuery),
// We can specify a different node to run the query from; in
// this case, we can tailor the search within #section.
chromedp.Text(".content", &queryFromNode, chromedp.ByQuery, chromedp.FromNode(sectionNode)),
// A CSS selector like "#section > .content" achieves the same
// here, but FromNode allows us to use a node obtained by an
// entirely separate step, allowing for custom logic.
chromedp.Text("#section > .content", &queryNestedSelector, chromedp.ByQuery),
); err != nil {
log.Fatal(err)
}
fmt.Println("Simple query from the document root:", queryRoot)
fmt.Println("Simple query from the section node:", queryFromNode)
fmt.Println("Nested query from the document root:", queryNestedSelector)
// Output:
// Simple query from the document root: outer content
// Simple query from the section node: inner content
// Nested query from the document root: inner content
}
func Example_dump() {
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
ts := httptest.NewServer(writeHTML(`<!doctype html>
<html>
<body>
<div id="content" style="display:block;">the content</div>
</body>
</html>`))
defer ts.Close()
const expr = `(function(d, id, v) {
var b = d.querySelector('body');
var el = d.createElement('div');
el.id = id;
el.innerText = v;
b.insertBefore(el, b.childNodes[0]);
})(document, %q, %q);`
s := fmt.Sprintf(expr, "thing", "a new thing!")
var buf bytes.Buffer
if err := chromedp.Run(ctx,
chromedp.Navigate(ts.URL),
chromedp.WaitVisible(`#content`),
chromedp.Evaluate(s, nil),
chromedp.WaitVisible(`#thing`),
chromedp.Dump(`document`, &buf, chromedp.ByJSPath),
); err != nil {
log.Fatal(err)
}
fmt.Println("Document tree:")
fmt.Print(buf.String())
// Output:
// Document tree:
// #document <Document>
// html <DocumentType>
// html
// head
// body
// div#thing
// #text "a new thing!"
// div#content [style="display:block;"]
// #text "the content"
}
func Example_documentDump() {
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
ts := httptest.NewServer(writeHTML(`<!doctype html>
<html>
<body>
<div id="content" style="display:block;">the content</div>
</body>
</html>`))
defer ts.Close()
const expr = `(function(d, id, v) {
var b = d.querySelector('body');
var el = d.createElement('div');
el.id = id;
el.innerText = v;
b.insertBefore(el, b.childNodes[0]);
})(document, %q, %q);`
s := fmt.Sprintf(expr, "thing", "a new thing!")
var nodes []*cdp.Node
if err := chromedp.Run(ctx,
chromedp.Navigate(ts.URL),
chromedp.Nodes(`document`, &nodes,
chromedp.ByJSPath, chromedp.Populate(-1, true)),
chromedp.WaitVisible(`#content`),
chromedp.Evaluate(s, nil),
chromedp.WaitVisible(`#thing`),
); err != nil {
log.Fatal(err)
}
fmt.Println("Document tree:")
fmt.Print(nodes[0].Dump(" ", " ", false))
// Output:
// Document tree:
// #document <Document>
// html <DocumentType>
// html
// head
// body
// div#thing
// #text "a new thing!"
// div#content [style="display:block;"]
// #text "the content"
}
func ExampleFullScreenshot() {
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
var buf []byte
if err := chromedp.Run(ctx,
chromedp.Navigate(`https://google.com`),
chromedp.FullScreenshot(&buf, 90),
); err != nil {
log.Fatal(err)
}
if err := os.WriteFile("fullScreenshot.jpeg", buf, 0o644); err != nil {
log.Fatal(err)
}
fmt.Println("wrote fullScreenshot.jpeg")
// Output:
// wrote fullScreenshot.jpeg
}
func ExampleEvaluate() {
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
// Ignore the result:
{
if err := chromedp.Run(ctx,
chromedp.Evaluate(`window.scrollTo(0, 100)`, nil),
); err != nil {
log.Fatal(err)
}
}
// Receive a primary value:
{
var sum int
if err := chromedp.Run(ctx,
chromedp.Evaluate(`1+2`, &sum),
); err != nil {
log.Fatal(err)
}
fmt.Println(sum)
}
// ErrJSUndefined:
{
var val int
if err := chromedp.Run(ctx,
chromedp.Evaluate(`undefined`, &val),
); err != nil {
fmt.Println(err)
}
}
// ErrJSNull:
{
var val int
if err := chromedp.Run(ctx,
chromedp.Evaluate(`null`, &val),
); err != nil {
fmt.Println(err)
}
}
// Accept undefined/null result:
{
var val *int
if err := chromedp.Run(ctx,
chromedp.Evaluate(`undefined`, &val),
); err != nil {
log.Fatal(err)
}
fmt.Println(val)
}
// Receive an array value:
{
var val []int
if err := chromedp.Run(ctx,
chromedp.Evaluate(`[1,2]`, &val),
); err != nil {
log.Fatal(err)
}
fmt.Println(val)
}
// Map and Slice accept undefined/null:
{
var val []int
if err := chromedp.Run(ctx,
chromedp.Evaluate(`null`, &val),
); err != nil {
log.Fatal(err)
}
fmt.Println("slice is nil:", val == nil)
}
// Receive the raw bytes:
{
var buf []byte
if err := chromedp.Run(ctx,
chromedp.Evaluate(`alert`, &buf),
); err != nil {
log.Fatal(err)
}
fmt.Printf("%s\n", buf)
}
// Receive the RemoteObject:
{
var res *runtime.RemoteObject
if err := chromedp.Run(ctx,
chromedp.Evaluate(`alert`, &res),
); err != nil {
log.Fatal(err)
}
if res.ObjectID != "" {
fmt.Println("objectId is present")
}
}
// Output:
// 3
// encountered an undefined value
// encountered a null value
// <nil>
// [1 2]
// slice is nil: true
// {}
// objectId is present
}