-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmicrodata.go
255 lines (219 loc) · 6.26 KB
/
microdata.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
/*
This is free and unencumbered software released into the public domain. For more
information, see <http://unlicense.org/> or the accompanying UNLICENSE file.
*/
// Package microdata provides types and functions for paring microdata from web pages.
// See http://www.w3.org/TR/microdata/ for more information about Microdata
package microdata
import (
"bytes"
"encoding/json"
"io"
"net/url"
"strings"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
type valueList []interface{}
type propertyMap map[string]valueList
// Item represents a microdata item
type Item struct {
Properties propertyMap `json:"properties"`
Types []string `json:"type,omitempty"`
ID string `json:"id,omitempty"`
}
// NewItem creates a new microdata item
func NewItem() *Item {
return &Item{
Properties: make(propertyMap, 0),
Types: make([]string, 0),
}
}
// AddString adds a string type item property value
func (i *Item) AddString(property string, value string) {
i.Properties[property] = append(i.Properties[property], value)
}
// AddItem adds an Item type item property value
func (i *Item) AddItem(property string, value *Item) {
i.Properties[property] = append(i.Properties[property], value)
}
// AddType adds a type to the item
func (i *Item) AddType(value string) {
i.Types = append(i.Types, value)
}
// Microdata represents a set of microdata items
type Microdata struct {
Items []*Item `json:"items"`
}
// NewMicrodata creates a new microdata set
func NewMicrodata() *Microdata {
return &Microdata{
Items: make([]*Item, 0),
}
}
// AddItem adds an item to the microdata set
func (m *Microdata) AddItem(value *Item) {
m.Items = append(m.Items, value)
}
// JSON converts the microdata set to JSON
func (m *Microdata) JSON() ([]byte, error) {
b, err := json.Marshal(m)
if err != nil {
return nil, err
}
return b, nil
}
// Parser is an HTML parser that extracts microdata
type Parser struct {
r io.Reader
data *Microdata
base *url.URL
identifiedNodes map[string]*html.Node
}
// NewParser creates a new parser for extracting microdata
// r is a reader over an HTML document
// base is the base URL for resolving relative URLs
func NewParser(r io.Reader, base *url.URL) *Parser {
return &Parser{
r: r,
data: NewMicrodata(),
base: base,
}
}
// Parse the document and return a Microdata set
func (p *Parser) Parse() (*Microdata, error) {
tree, err := html.Parse(p.r)
if err != nil {
return nil, err
}
topLevelItemNodes := make([]*html.Node, 0)
p.identifiedNodes = make(map[string]*html.Node, 0)
walk(tree, func(n *html.Node) {
if n.Type == html.ElementNode {
if _, exists := getAttr("itemscope", n); exists {
if _, exists := getAttr("itemprop", n); !exists {
topLevelItemNodes = append(topLevelItemNodes, n)
}
}
if id, exists := getAttr("id", n); exists {
p.identifiedNodes[id] = n
}
}
})
for _, node := range topLevelItemNodes {
p.data.Items = append(p.data.Items, p.readItem(nil, node))
}
return p.data, nil
}
func (p *Parser) readItem(item *Item, node *html.Node) *Item {
var parent *Item
if _, exists := getAttr("itemscope", node); exists {
parent, item = item, NewItem()
if itemtypes, exists := getAttr("itemtype", node); exists {
for _, itemtype := range strings.Split(strings.TrimSpace(itemtypes), " ") {
itemtype = strings.TrimSpace(itemtype)
if itemtype != "" {
item.Types = append(item.Types, itemtype)
}
}
// itemid only valid when itemscope and itemtype are both present
if itemid, exists := getAttr("itemid", node); exists {
if parsedURL, err := p.base.Parse(itemid); err == nil {
item.ID = parsedURL.String()
}
}
}
if itemrefs, exists := getAttr("itemref", node); exists {
for _, itemref := range strings.Split(strings.TrimSpace(itemrefs), " ") {
itemref = strings.TrimSpace(itemref)
if refnode, exists := p.identifiedNodes[itemref]; exists {
if refnode != node {
p.readItem(item, refnode)
}
}
}
}
}
if itemprop, exists := getAttr("itemprop", node); exists {
if parent != nil {
// an itemprop on an itemscope has value of the item created by the itemscope
for _, propertyName := range strings.Split(strings.TrimSpace(itemprop), " ") {
propertyName = strings.TrimSpace(propertyName)
if propertyName != "" {
parent.AddItem(propertyName, item)
}
}
} else {
var propertyValue string
switch node.DataAtom {
case atom.Meta:
if val, exists := getAttr("content", node); exists {
propertyValue = val
}
case atom.Audio, atom.Embed, atom.Iframe, atom.Img, atom.Source, atom.Track, atom.Video:
if urlValue, exists := getAttr("src", node); exists {
if parsedURL, err := p.base.Parse(urlValue); err == nil {
propertyValue = parsedURL.String()
}
}
case atom.A, atom.Area, atom.Link:
if urlValue, exists := getAttr("href", node); exists {
if parsedURL, err := p.base.Parse(urlValue); err == nil {
propertyValue = parsedURL.String()
}
}
case atom.Object:
if urlValue, exists := getAttr("data", node); exists {
propertyValue = urlValue
}
case atom.Data, atom.Meter:
if urlValue, exists := getAttr("value", node); exists {
propertyValue = urlValue
}
case atom.Time:
if urlValue, exists := getAttr("datetime", node); exists {
propertyValue = urlValue
}
default:
var text bytes.Buffer
walk(node, func(n *html.Node) {
if n.Type == html.TextNode {
text.WriteString(n.Data)
}
})
propertyValue = text.String()
}
if len(propertyValue) > 0 {
for _, propertyName := range strings.Split(strings.TrimSpace(itemprop), " ") {
propertyName = strings.TrimSpace(propertyName)
if propertyName != "" {
item.AddString(propertyName, propertyValue)
}
}
}
}
}
for child := node.FirstChild; child != nil; {
p.readItem(item, child)
child = child.NextSibling
}
return item
}
func getAttr(name string, node *html.Node) (string, bool) {
for _, a := range node.Attr {
if a.Key == name {
return a.Val, true
}
}
return "", false
}
func walk(parent *html.Node, fn func(n *html.Node)) {
if parent == nil {
return
}
fn(parent)
for child := parent.FirstChild; child != nil; {
walk(child, fn)
child = child.NextSibling
}
}