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
|
package findlinks
import (
"fmt"
"io"
"strings"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
// Parse collects the unmarshalled [Link] data from the HTML document
// represented by r. The data is returned as a slice, along with an
// error.
func Parse(r io.Reader) ([]Link, error) {
doc, err := html.Parse(r)
if err != nil {
return nil, fmt.Errorf("can't parse html reader: %w", err)
}
return parseLinks(doc), nil
}
// parseLinks returns a [Link] slice from doc. Each element is an
// "unmarshalled" version of an anchor tag element inside doc.
func parseLinks(doc *html.Node) []Link {
linkNodes := harvestLinkNodes(doc)
var links []Link
for _, linkNode := range linkNodes {
var link Link
// Get the link's inner text.
link.Text = harvestText(linkNode)
// Get the href attribute.
for _, a := range linkNode.Attr {
if a.Key == "href" {
link.Href = a.Val
break
}
}
links = append(links, link)
}
return links
}
// harvestText returns the harvestText contained inside n.
//
// Note that the harvestText could be under many layers of HTML
// nesting. Hence the [html.ElementNode] case calls harvestText recursively.
//
// For the current project, harvestText's argument is always an
// anchor-tag element.
func harvestText(n *html.Node) string {
switch n.Type {
// The text of an [html.TextNode] is its [html.Node.Data]
// field.
case html.TextNode:
return n.Data
// The text of an [html.ElementNode] is the aggregate of the
// text of its children. We can assume that text is otherwise
// correctly formatted in terms of spacing (i.e. markup
// doesn't otherwise introduce run-on words unless intended,
// for example "I am on <strong>GitHub</strong>!")
case html.ElementNode:
var builder strings.Builder
for child := n.FirstChild; child != nil; child = child.NextSibling {
builder.WriteString(harvestText(child))
}
rawResult := builder.String()
fields := strings.Fields(rawResult)
return strings.Join(fields, " ")
// Any other kind of node (e.g. [html.CommentNode]) doesn't
// have text.
default:
return ""
}
}
// harvestLinkNodes harvests all of the link nodes contained inside n.
//
// For the current project, harvestLinkNodes' argument is always the
// top-level document node.
func harvestLinkNodes(node *html.Node) []*html.Node {
var links []*html.Node
for child := range node.Descendants() {
if child.Type == html.ElementNode && child.DataAtom == atom.A {
links = append(links, child)
}
}
return links
}
|