-
Notifications
You must be signed in to change notification settings - Fork 1
/
htmlParse.go
109 lines (95 loc) · 2 KB
/
htmlParse.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
100
101
102
103
104
105
106
107
108
109
package main
import (
"fmt"
"os"
"strings"
"golang.org/x/net/html"
)
type label struct {
text string
forInput string
}
type printable struct {
paragraphs []string
labels []label
}
func getPrintableContent(htmlFileName string) (*printable, error) {
f, err := os.Open(htmlFileName)
if err != nil {
return nil, fmt.Errorf("fail to open %v: %v", f, err)
}
defer f.Close()
doc, err := html.Parse(f)
if err != nil {
return nil, fmt.Errorf("fail to parse %v: %v", f, err)
}
p := newPrintable()
extractIntoPrintable(doc, p)
return p, nil
}
func newPrintable() *printable {
return &printable{
paragraphs: make([]string, 0),
labels: make([]label, 0),
}
}
func extractIntoPrintable(n *html.Node, p *printable) {
if isParagraph(n) {
p.paragraphs = append(p.paragraphs, strings.TrimSpace(buildParagraph(n)))
} else if isLabel(n) {
p.labels = append(p.labels, buildLabel(n))
} else {
for c := n.FirstChild; c != nil; c = c.NextSibling {
extractIntoPrintable(c, p)
}
}
}
func isParagraph(n *html.Node) bool {
return n.Type == html.ElementNode && n.Data == "p"
}
func buildParagraph(n *html.Node) string {
var p string
if n.Type == html.TextNode {
trimmed := make([]rune, 0)
var prev rune
for _, c := range n.Data {
if !(c == ' ' && prev == ' ' || c == '\n') {
trimmed = append(trimmed, c)
}
prev = c
}
p += string(trimmed)
}
if n.Type == html.ElementNode {
if n.Data != "p" {
p += "<" + n.Data + ">"
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
p += buildParagraph(c)
}
if n.Data != "p" {
p += "</" + n.Data + ">"
}
}
return p
}
func isLabel(n *html.Node) bool {
return n.Type == html.ElementNode && n.Data == "label"
}
func buildLabel(n *html.Node) label {
var l label
for _, atr := range n.Attr {
if atr.Key == "for" {
l.forInput = atr.Val
}
}
if n.Type == html.ElementNode {
for c := n.FirstChild; c != nil; c = c.NextSibling {
if c.Type == html.TextNode {
l.text = c.Data
break
}
}
}
return l
}