-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathlist.go
99 lines (83 loc) · 1.86 KB
/
list.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
package ant
import (
"strings"
"github.com/yields/ant/internal/scan"
"github.com/yields/ant/internal/selectors"
"golang.org/x/net/html"
)
var (
// Scanner represents a node scanner.
scanner = scan.NewScanner()
)
// List represents a list of nodes.
//
// The list wraps the html node slice with
// helper methods to extract data and manipulate
// the list.
type List []*html.Node
// Query returns a list of nodes matching selector.
//
// If the selector is invalid, the method returns a nil list.
func (l List) Query(selector string) List {
var ret List
if sel, err := selectors.Compile(selector); err == nil {
for _, n := range l {
ret = append(ret, sel.MatchAll(n)...)
}
}
return ret
}
// Is returns true if any of the nodes matches selector.
func (l List) Is(selector string) (matched bool) {
if sel, err := selectors.Compile(selector); err == nil {
for _, n := range l {
if sel.Match(n) {
matched = true
break
}
}
}
return
}
// At returns a list that contains the node at index i.
//
// If a negative index is provided the method returns
// node from the end of the list.
func (l List) At(i int) List {
if i >= 0 {
if len(l) > i {
return List{l[i]}
}
return List{}
}
if i = len(l) + i; i >= 0 {
if len(l) > i {
return List{l[i]}
}
}
return List{}
}
// Text returns inner text of the first node..
func (l List) Text() string {
var b strings.Builder
for _, n := range l {
b.WriteString(scan.Text(n))
}
return b.String()
}
// Attr returns the attribute value of key of the first node.
func (l List) Attr(key string) (string, bool) {
for _, n := range l {
return scan.Attr(n, key)
}
return "", false
}
// Scan scans all items into struct `dst`.
//
// The method scans data from the 1st node.
func (l List) Scan(dst interface{}) error {
for _, n := range l {
return scanner.Scan(dst, n, scan.Options{})
}
return nil
}