-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhtml.go
More file actions
64 lines (52 loc) · 1.24 KB
/
Copy pathhtml.go
File metadata and controls
64 lines (52 loc) · 1.24 KB
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
package main
import (
"io"
"log"
"strings"
"golang.org/x/net/html"
)
// Parse the html tree
func Parse(r io.Reader) Element {
doc, err := html.Parse(r)
if err != nil {
log.Fatal(err)
}
node := MakeTree(doc)
return node
}
// MakeTree creates an Element Tree
func MakeTree(n *html.Node) Element {
// if n.Type == html.ElementNode && n.Data == "a" {
// for _, a := range n.Attr {
// if a.Key == "href" {
// fmt.Println(a.Val)
// break
// }
// }
// }
root := MakeElementNode("a")
root.SetData(n.Data)
if n.Type == html.ElementNode {
root.nodeType = ElementNode
// fmt.Println("element node: '" + n.Data + "' " + n.DataAtom.String())
for _, attribute := range n.Attr {
root.attributes[attribute.Key] = attribute.Val
}
} else {
if len(SpaceFieldsJoin(n.Data)) > 0 {
root.nodeType = TextNode
}
// fmt.Println("text node: '" + n.Data + "' " + n.DataAtom.String())
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
if len(SpaceFieldsJoin(c.Data)) > 0 {
root.Add(MakeTree(c))
}
}
return root
}
// SpaceFieldsJoin quickly removes all whitespace from a string
// @author: https://stackoverflow.com/a/32081891
func SpaceFieldsJoin(str string) string {
return strings.Join(strings.Fields(str), "")
}