forked from chromedp/chromedp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
565 lines (488 loc) · 13.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
package chromedp_test
import (
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"time"
"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"
"github.com/chromedp/chromedp"
"github.com/chromedp/chromedp/device"
)
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 {
panic(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 {
panic(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 {
panic(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 {
panic(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 {
panic(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 := ioutil.TempDir("", "chromedp-example")
if err != nil {
panic(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 {
panic(err)
}
path := filepath.Join(dir, "DevToolsActivePort")
bs, err := ioutil.ReadFile(path)
if err != nil {
panic(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 {
panic(err)
}
for i := 0; i < 2; i++ {
// look at the page twice, with a timeout set up; we skip
// cancels for the sake of brevity
ctx, _ := context.WithTimeout(ctx, time.Second)
ctx, _ = chromedp.NewContext(ctx)
var cookies string
if err := chromedp.Run(ctx,
chromedp.Navigate(ts.URL),
chromedp.Text("#cookies", &cookies),
); err != nil {
panic(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 {
panic(err)
}
// same browser, second tab
ctx2, _ := chromedp.NewContext(ctx1)
// ensure the second tab is created
if err := chromedp.Run(ctx2); err != nil {
panic(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>")
fmt.Printf("* %s\n", s)
gotException <- true
}
})
if err := chromedp.Run(ctx, chromedp.Navigate(ts.URL)); err != nil {
panic(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 property 'throwsException' of null
// 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 {
panic(err)
}
newCtx, cancel := chromedp.NewContext(ctx, chromedp.WithTargetID(<-ch))
defer cancel()
var urlstr string
if err := chromedp.Run(newCtx, chromedp.Location(&urlstr)); err != nil {
panic(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 {
panic(err)
}
}()
}
})
if err := chromedp.Run(ctx,
chromedp.Navigate(ts.URL),
chromedp.Click("#alert", chromedp.ByID),
); err != nil {
panic(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.Click("#content", chromedp.ByID),
chromedp.OuterHTML("#content", &outerAfter),
); err != nil {
panic(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://google.com/`),
chromedp.SendKeys(`input[name=q]`, "what's my user agent?\n"),
chromedp.WaitVisible(`#rso`, chromedp.ByID),
chromedp.CaptureScreenshot(&buf),
); err != nil {
panic(err)
}
if err := ioutil.WriteFile("google-iphone7.png", buf, 0o644); err != nil {
panic(err)
}
}
func ExamplePrintToPDF() {
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
var buf []byte
if err := chromedp.Run(ctx,
chromedp.Navigate(`https://godoc.org/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 {
panic(err)
}
if err := ioutil.WriteFile("page.pdf", buf, 0o644); err != nil {
panic(err)
}
}
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 {
panic(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 {
panic(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 {
panic(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_documentDump() {
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
ts := httptest.NewServer(writeHTML(`<!doctype html>
<html>
<body>
<div id="content">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);`
var nodes []*cdp.Node
if err := chromedp.Run(ctx,
chromedp.Navigate(ts.URL),
chromedp.Nodes(`document`, &nodes, chromedp.ByJSPath),
chromedp.WaitVisible(`#content`),
chromedp.ActionFunc(func(ctx context.Context) error {
s := fmt.Sprintf(expr, "thing", "a new thing!")
_, exp, err := runtime.Evaluate(s).Do(ctx)
if err != nil {
return err
}
if exp != nil {
return exp
}
return nil
}),
chromedp.WaitVisible(`#thing`),
); err != nil {
panic(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
// #text "the content"
}