/
scraper.go
227 lines (192 loc) · 4.9 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
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
package scraper
import (
"encoding/json"
"fmt"
"github.com/PuerkitoBio/goquery"
"github.com/reaper47/recipya/internal/models"
"github.com/reaper47/recipya/internal/services"
"net/http"
"net/url"
"strings"
)
const atContext = "https://schema.org"
// HTTPClient is an interface for making HTTP requests.
type HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}
// IScraper is the scraper's interface.
type IScraper interface {
Scrape(url string, files services.FilesService) (models.RecipeSchema, error)
}
// Scraper represents the IScraper's implementation.
type Scraper struct {
Client HTTPClient
}
// NewScraper creates a new Scraper.
func NewScraper(client HTTPClient) *Scraper {
return &Scraper{
Client: client,
}
}
// Scrape extracts the recipe from the given URL. An error will be
// returned when the URL cannot be parsed.
func (s *Scraper) Scrape(url string, files services.FilesService) (models.RecipeSchema, error) {
host := getHost(url)
if host == "bergamot" {
return s.scrapeBergamot(url)
} else if host == "foodbag" {
return s.scrapeFoodbag(url)
} else if host == "monsieur-cuisine" {
doc, err := s.fetchDocument(url)
if err != nil {
return models.RecipeSchema{}, err
}
return s.scrapeMonsieurCuisine(doc, url, files)
} else if host == "quitoque" {
return s.scrapeQuitoque(url)
} else if host == "reddit" {
url = strings.Replace(url, "www", "old", 1)
}
doc, err := s.fetchDocument(url)
if err != nil {
return models.RecipeSchema{}, err
}
rs, err := scrapeWebsite(doc, host)
if err != nil {
return rs, ErrNotImplemented
}
if rs.AtContext == "" {
rs.AtContext = atContext
}
if rs.Category.Value == "" {
rs.Category.Value = "uncategorized"
}
if rs.AtType.Value == "" {
rs.AtType.Value = "Recipe"
}
if rs.URL == "" {
rs.URL = url
}
imageUUID, err := files.ScrapeAndStoreImage(rs.Image.Value)
if err != nil {
return rs, err
}
rs.Image.Value = imageUUID.String()
return rs, nil
}
func (s *Scraper) fetchDocument(url string) (*goquery.Document, error) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
const mozilla = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:122.0) Gecko/20100101 Firefox/122.0"
host := getHost(url)
switch host {
case "aberlehome", "bettybossi", "marmiton", "puurgezond", "reddit", "thepalatablelife":
req.Header.Set("User-Agent", mozilla)
case "ah":
req.Header.Set("Accept-Language", "nl")
req.Header.Set("User-Agent", mozilla)
}
res, err := s.Client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
// Some websites require page reloads
if host == "bettybossi" {
res, err = s.Client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
}
if res.StatusCode >= http.StatusBadRequest {
return nil, fmt.Errorf("could not fetch (%d), try the bookmarklet", res.StatusCode)
}
return goquery.NewDocumentFromReader(res.Body)
}
func getHost(rawURL string) string {
u, err := url.Parse(rawURL)
if err != nil {
return ""
}
parts := strings.Split(u.Hostname(), ".")
switch len(parts) {
case 4:
if parts[1] == "m" {
return parts[2]
}
return parts[1]
case 3:
s := parts[0]
if s == "recipes" || s == "receitas" || s == "cooking" || s == "news" || s == "mobile" ||
s == "dashboard" || s == "fr" || s == "blog" || s == "old" {
return parts[1]
}
if parts[1] == "wikibooks" || parts[1] == "tesco" || parts[1] == "expressen" {
return parts[1]
}
if s != "www" {
return s
}
return parts[1]
default:
if len(parts) > 1 {
return parts[len(parts)-2]
}
return ""
}
}
func parseLdJSON(root *goquery.Document) (models.RecipeSchema, error) {
for _, node := range root.Find("script[type='application/ld+json']").Nodes {
if node.FirstChild == nil {
continue
}
var rs models.RecipeSchema
err := json.Unmarshal([]byte(strings.ReplaceAll(node.FirstChild.Data, "\n", "")), &rs)
if err != nil {
var xrs []models.RecipeSchema
err = json.Unmarshal([]byte(node.FirstChild.Data), &xrs)
if err != nil {
continue
}
for _, rs := range xrs {
if rs.AtType.Value == "Recipe" {
rs.AtContext = atContext
return rs, nil
}
}
continue
}
if rs.AtType.Value != "Recipe" {
continue
}
rs.AtContext = atContext
return rs, nil
}
return models.RecipeSchema{}, ErrNotImplemented
}
type graph struct {
AtContext string `json:"@context"`
AtGraph []models.RecipeSchema `json:"@graph"`
}
func parseGraph(root *goquery.Document) (models.RecipeSchema, error) {
for _, node := range root.Find("script[type='application/ld+json']").Nodes {
if node.FirstChild == nil {
continue
}
var g graph
err := json.Unmarshal([]byte(node.FirstChild.Data), &g)
if err != nil {
continue
}
for _, r := range g.AtGraph {
if r.AtType.Value == "Recipe" {
r.AtContext = atContext
return r, nil
}
}
}
return models.RecipeSchema{}, ErrNotImplemented
}