forked from adamschwartz/web.scraper.workers.dev
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scraper.js
108 lines (81 loc) · 2.42 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
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
}
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