-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscraper.go
102 lines (80 loc) · 1.92 KB
/
scraper.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
package main
import (
"fmt"
"net/http"
"strings"
"github.com/PuerkitoBio/goquery"
)
// Scraper for each website
type Scraper struct {
url string
doc *goquery.Document
}
// NewScraper builds a new scraper for the website
func NewScraper(u string) *Scraper {
if !strings.HasPrefix(u, "http") {
return nil
}
response, err := http.Get(u)
if err != nil {
fmt.Println(err)
return nil
}
defer response.Body.Close()
d, err := goquery.NewDocumentFromReader(response.Body)
if err != nil {
fmt.Println(err)
return nil
}
return &Scraper{
url: u,
doc: d,
}
}
// Body returns a string with the body of the page
func (s *Scraper) Body() string {
body := s.doc.Find("body").Text()
// Remove leading/ending white spaces
body = strings.TrimSpace(body)
return body
}
func (s *Scraper) buildLink(href string) string {
var link string
if strings.HasPrefix(href, "/") {
link = strings.Join([]string{s.url, href}, "")
} else {
link = href
}
link = strings.TrimRight(link, "/")
link = strings.TrimRight(link, ":")
return link
}
// Links returns an array with all the links from the website
func (s *Scraper) Links() []string {
links := make([]string, 0)
var link string
s.doc.Find("body a").Each(func(index int, item *goquery.Selection) {
link = ""
linkTag := item
href, _ := linkTag.Attr("href")
if !strings.HasPrefix(href, "#") && !strings.HasPrefix(href, "javascript") {
link = s.buildLink(href)
if link != "" {
links = append(links, link)
}
}
})
return links
}
// MetaDataInformation returns the title and description from the page
func (s *Scraper) MetaDataInformation() (string, string) {
var t string
var d string
t = s.doc.Find("title").Contents().Text()
s.doc.Find("meta").Each(func(index int, item *goquery.Selection) {
if item.AttrOr("name", "") == "description" || item.AttrOr("property", "") == "og:description" {
d = item.AttrOr("content", "")
}
})
return t, d
}