-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
75 lines (68 loc) · 1.47 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
package helper_test
import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"time"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/chromedp"
helper "github.com/go-oss/chromedp-helper"
)
func Example_navigate() {
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
ts := httptest.NewServer(exampleHandler())
defer ts.Close()
var next string
var title string
tasks := chromedp.Tasks{
// It is necessary in the helper methods.
network.Enable(),
helper.EnableLifeCycleEvents(),
helper.Navigate(ts.URL, time.Minute),
chromedp.AttributeValue("//a[contains(., 'Link')]", "href", &next, nil),
helper.Navigate(helper.URL(ts.URL, "%s", &next), time.Minute),
chromedp.Title(&title),
}
err := chromedp.Run(ctx, tasks)
if err != nil {
panic(err)
}
fmt.Println(title)
// Output: Example
}
func exampleHandler() http.Handler {
index := strings.TrimSpace(`
<DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<a href="/next">Link</a>
</body>
</html>`)
next := strings.TrimSpace(`
<DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
Example
</body>
</html>`)
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
io.WriteString(w, index)
})
mux.HandleFunc("/next", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
io.WriteString(w, next)
})
return mux
}