forked from adamschwartz/web.scraper.workers.dev
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scraper.js
176 lines (133 loc) · 3.98 KB
/
scraper.js
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
const cleanText = s => s.trim().replace(/\s\s+/g, ' ')
class Scraper {
constructor() {
this.rewriter = new HTMLRewriter()
return this
}
async fetch(url) {
this.url = url
this.response = await fetch(url)
const server = this.response.headers.get('server')
const isThisWorkerErrorNotErrorWithinScrapedSite = (
[530, 503, 502, 403, 400].includes(this.response.status) &&
(server === 'cloudflare' || !server /* Workers preview editor */)
)
if (isThisWorkerErrorNotErrorWithinScrapedSite) {
throw new Error(`Status ${ this.response.status } requesting ${ url }`)
}
return this
}
async scrape() {
const epicuriousMap = {
title: "h1",
excerpt: '[data-testid="BodyWrapper"]',
ingredients_raw: '[data-testid="IngredientList"]',
steps_raw: '[data-testid="InstructionsWrapper"]',
image_url: '[data-testid="ContentHeaderLeadAsset"] picture img'
}
const matches = {}
Object.entries(epicuriousMap).forEach(([key, selector]) => {
matches[key] = []
let nextText = ''
this.rewriter.on(selector, {
element(element) {
matches[key].push(true)
nextText = ''
if (element.hasAttribute("src")) {
matches[key].push(element.getAttribute("src"))
}
},
text(text) {
nextText += text.text
if (text.lastInTextNode) {
nextText += ' '
matches[key].push(nextText)
nextText = ''
}
}
})
return matches
})
const transformed = this.rewriter.transform(this.response)
await transformed.arrayBuffer()
Object.entries(epicuriousMap).forEach(([key, selector]) => {
const nodeCompleteTexts = []
let nextText = ''
matches[key].forEach(text => {
if (text === true) {
if (nextText.trim() !== '') {
nodeCompleteTexts.push(cleanText(nextText))
nextText = ''
}
} else {
nextText += text
}
})
const lastText = cleanText(nextText)
if (lastText !== '') nodeCompleteTexts.push(lastText)
matches[key] = nodeCompleteTexts
})
return matches
}
querySelector(selector) {
this.selector = selector
return this
}
async getText({ spaced }) {
const matches = {}
const selectors = new Set(this.selector.split(',').map(s => s.trim()))
selectors.forEach((selector) => {
matches[selector] = []
let nextText = ''
this.rewriter.on(selector, {
element(element) {
matches[selector].push(true)
nextText = ''
},
text(text) {
nextText += text.text
if (text.lastInTextNode) {
if (spaced) nextText += ' '
matches[selector].push(nextText)
nextText = ''
}
}
})
})
const transformed = this.rewriter.transform(this.response)
await transformed.arrayBuffer()
selectors.forEach((selector) => {
const nodeCompleteTexts = []
let nextText = ''
matches[selector].forEach(text => {
if (text === true) {
if (nextText.trim() !== '') {
nodeCompleteTexts.push(cleanText(nextText))
nextText = ''
}
} else {
nextText += text
}
})
const lastText = cleanText(nextText)
if (lastText !== '') nodeCompleteTexts.push(lastText)
matches[selector] = nodeCompleteTexts
})
return selectors.length === 1 ? matches[selectors[0]] : matches
}
async getAttribute(attribute) {
class AttributeScraper {
constructor(attr) {
this.attr = attr
}
element(element) {
if (this.value) return
this.value = element.getAttribute(this.attr)
}
}
const scraper = new AttributeScraper(attribute)
await new HTMLRewriter().on(this.selector, scraper).transform(this.response).arrayBuffer()
return scraper.value || ''
}
}
export default Scraper