-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmetadata-crawler.go
87 lines (78 loc) · 2.21 KB
/
metadata-crawler.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
// Import the net/http and golang.org/x/net/html packages
import (
"fmt"
"net/http"
"strings"
"golang.org/x/net/html"
)
// Define a function that takes a URL as input and returns a map with the metadata
func getMetadata(url string) (map[string]string, error) {
// Make a GET request and check for errors
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// Parse the HTML response and check for errors
doc, err := html.Parse(resp.Body)
if err != nil {
return nil, err
}
// Define the selectors for the metadata elements
titleSelector := "head > title"
descriptionSelector := "meta[name=description]"
keywordsSelector := "meta[name=keywords]"
// Create a map to store the metadata
metadata := make(map[string]string)
// Define a recursive function to traverse the HTML tree
var traverse func(*html.Node)
traverse = func(n *html.Node) {
// If the node is an element
if n.Type == html.ElementNode {
// If the node matches the title selector
if n.Data == "title" && strings.Contains(titleSelector, n.Parent.Data) {
// Get the text content of the node
if n.FirstChild != nil {
metadata["title"] = n.FirstChild.Data
}
}
// If the node matches the meta selector
if n.Data == "meta" {
// Get the name and content attributes of the node
var name, content string
for _, a := range n.Attr {
if a.Key == "name" {
name = a.Val
}
if a.Key == "content" {
content = a.Val
}
}
// If the name matches the description or keywords selector
if name == "description" && descriptionSelector == "meta[name=description]" {
metadata["description"] = content
}
if name == "keywords" && keywordsSelector == "meta[name=keywords]" {
metadata["keywords"] = content
}
}
}
// Recursively visit the child nodes
for c := n.FirstChild; c != nil; c = c.NextSibling {
traverse(c)
}
}
// Start the traversal from the root node
traverse(doc)
// Return the metadata map
return metadata, nil
}
// Call the function with an example URL and print the result
func main() {
metadata, err := getMetadata("https://www.cloudfrl.com")
if err != nil {
fmt.Println(err)
} else {
fmt.Println(metadata)
}
}