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
|
package findlinks
import (
"fmt"
"io"
"strings"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
// A Link encapsulates the data harvested from a link.
type Link struct {
Href string
Text string
}
// FindLinks consumes the given [io.Reader], scraping it of anchor
// tags. Each anchor tag is "unmarshalled" into a [Link]. The
// resulting slice of Links is returned, along with an error.
func FindLinks(r io.Reader) ([]Link, error) {
doc, err := html.Parse(r)
if err != nil {
return nil, fmt.Errorf("can't parse html reader: %w", err)
}
links := iterHTML(doc, nil)
return links, nil
}
// iterHTML recursively scans the HTML tree n for link data.
func iterHTML(n *html.Node, buffer []Link) []Link {
// Return if n doesn't contain the right kind of data, since
// we could potentially iterate twice over things like text
// nodes when calling extractText.
if n.Type != html.ElementNode && n.Type != html.DocumentNode {
return buffer
}
// If we've hit a link, go for it.
if n.Type == html.ElementNode && n.DataAtom == atom.A {
var link Link
// Href
link.Href = extractHref(n)
// Text
chunks := extractText(n, nil)
link.Text = strings.Join(chunks, " ")
buffer = append(buffer, link)
} else {
// If not a link, just dive down the tree looking for
// more links.
for c := n.FirstChild; c != nil; c = c.NextSibling {
buffer = iterHTML(c, buffer)
}
}
return buffer
}
// extractHref returns the first href attribute of anchor.
func extractHref(anchor *html.Node) string {
var href string
for _, a := range anchor.Attr {
if a.Key == atom.Href.String() {
href = a.Val
break
}
}
return href
}
// extractText recursively scans anchor to return the various nested
// pieces of text content.
func extractText(anchor *html.Node, buffer []string) []string {
for c := anchor.FirstChild; c != nil; c = c.NextSibling {
switch c.Type {
case html.TextNode:
buffer = append(buffer, c.Data)
case html.ElementNode:
buffer = extractText(c, buffer)
}
}
return buffer
}
|