-
Notifications
You must be signed in to change notification settings - Fork 527
Expand file tree
/
Copy pathroot-extractor.js
More file actions
273 lines (235 loc) · 7.18 KB
/
root-extractor.js
File metadata and controls
273 lines (235 loc) · 7.18 KB
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import Cleaners from 'cleaners';
import { convertNodeTo, makeLinksAbsolute } from 'utils/dom';
import GenericExtractor from './generic';
// Remove elements by an array of selectors
export function cleanBySelectors($content, $, { clean }) {
if (!clean) return $content;
$(clean.join(','), $content).remove();
return $content;
}
// Transform matching elements
export function transformElements($content, $, { transforms }) {
if (!transforms) return $content;
Reflect.ownKeys(transforms).forEach(key => {
const $matches = $(key, $content);
const value = transforms[key];
// If value is a string, convert directly
if (typeof value === 'string') {
$matches.each((index, node) => {
convertNodeTo($(node), $, transforms[key]);
});
} else if (typeof value === 'function') {
// If value is function, apply function to node
$matches.each((index, node) => {
const result = value($(node), $);
// If function returns a string, convert node to that value
if (typeof result === 'string') {
convertNodeTo($(node), $, result);
}
});
}
});
return $content;
}
function findMatchingSelector($, selectors, extractHtml, allowMultiple) {
return selectors.find(selector => {
if (Array.isArray(selector)) {
if (extractHtml) {
return selector.reduce((acc, s) => acc && $(s).length > 0, true);
}
const [s, attr] = selector;
if (attr)
return (
(allowMultiple || (!allowMultiple && $(s).length === 1)) &&
$(s).attr(attr) &&
$(s)
.attr(attr)
.trim() !== ''
);
selector = s;
}
return (
(allowMultiple || (!allowMultiple && $(selector).length === 1)) &&
$(selector)
.text()
.trim() !== ''
);
});
}
export function select(opts) {
const { $, type, extractionOpts, extractHtml = false } = opts;
// Skip if there's not extraction for this type
if (!extractionOpts) return null;
// If a string is hardcoded for a type (e.g., Wikipedia
// contributors), return the string
if (typeof extractionOpts === 'string') return extractionOpts;
const { selectors, defaultCleaner = true, allowMultiple } = extractionOpts;
const matchingSelector = findMatchingSelector(
$,
selectors,
extractHtml,
allowMultiple
);
if (!matchingSelector) return null;
function transformAndClean($node) {
makeLinksAbsolute($node, $, opts.url || '');
cleanBySelectors($node, $, extractionOpts);
transformElements($node, $, extractionOpts);
return $node;
}
function selectHtml() {
// If the selector type requests html as its return type
// transform and clean the element with provided selectors
let $content;
// If matching selector is an array, we're considering this a
// multi-match selection, which allows the parser to choose several
// selectors to include in the result. Note that all selectors in the
// array must match in order for this selector to trigger
if (Array.isArray(matchingSelector)) {
$content = $(matchingSelector.join(','));
const $wrapper = $('<div></div>');
$content.each((_, element) => {
$wrapper.append(element);
});
$content = $wrapper;
} else {
$content = $(matchingSelector);
}
// Wrap in div so transformation can take place on root element
$content.wrap($('<div></div>'));
$content = $content.parent();
$content = transformAndClean($content);
if (Cleaners[type]) {
Cleaners[type]($content, { ...opts, defaultCleaner });
}
if (allowMultiple) {
return $content
.children()
.toArray()
.map(el => $.html($(el)));
}
return $.html($content);
}
if (extractHtml) {
return selectHtml(matchingSelector);
}
let $match;
let result;
// if selector is an array (e.g., ['img', 'src']),
// extract the attr
if (Array.isArray(matchingSelector)) {
const [selector, attr, transform] = matchingSelector;
$match = $(selector);
$match = transformAndClean($match);
result = $match.map((_, el) => {
const item = $(el)
.attr(attr)
.trim();
return transform ? transform(item) : item;
});
} else {
$match = $(matchingSelector);
$match = transformAndClean($match);
result = $match.map((_, el) =>
$(el)
.text()
.trim()
);
}
result =
Array.isArray(result.toArray()) && allowMultiple
? result.toArray()
: result[0];
// Allow custom extractor to skip default cleaner
// for this type; defaults to true
if (defaultCleaner && Cleaners[type]) {
return Cleaners[type](result, { ...opts, ...extractionOpts });
}
return result;
}
export function selectExtendedTypes(extend, opts) {
const results = {};
Reflect.ownKeys(extend).forEach(t => {
if (!results[t]) {
results[t] = select({ ...opts, type: t, extractionOpts: extend[t] });
}
});
return results;
}
function extractResult(opts) {
const { type, extractor, fallback = true } = opts;
const result = select({ ...opts, extractionOpts: extractor[type] });
// If custom parser succeeds, return the result
if (result) {
return result;
}
// If nothing matches the selector, and fallback is enabled,
// run the Generic extraction
if (fallback) return GenericExtractor[type](opts);
return null;
}
const RootExtractor = {
extract(extractor = GenericExtractor, opts) {
const { contentOnly, extractedTitle } = opts;
// This is the generic extractor. Run its extract method
if (extractor.domain === '*') return extractor.extract(opts);
opts = {
...opts,
extractor,
};
if (contentOnly) {
const content = extractResult({
...opts,
type: 'content',
extractHtml: true,
title: extractedTitle,
});
return {
content,
};
}
const title = extractResult({ ...opts, type: 'title' });
const date_published = extractResult({ ...opts, type: 'date_published' });
const author = extractResult({ ...opts, type: 'author' });
const next_page_url = extractResult({ ...opts, type: 'next_page_url' });
const content = extractResult({
...opts,
type: 'content',
extractHtml: true,
title,
});
const lead_image_url = extractResult({
...opts,
type: 'lead_image_url',
content,
});
const excerpt = extractResult({ ...opts, type: 'excerpt', content });
const dek = extractResult({ ...opts, type: 'dek', content, excerpt });
const word_count = extractResult({ ...opts, type: 'word_count', content });
const direction = extractResult({ ...opts, type: 'direction', title });
const { url, domain } = extractResult({
...opts,
type: 'url_and_domain',
}) || { url: null, domain: null };
let extendedResults = {};
if (extractor.extend) {
extendedResults = selectExtendedTypes(extractor.extend, opts);
}
return {
title,
content,
author,
date_published,
lead_image_url,
dek,
next_page_url,
url,
domain,
excerpt,
word_count,
direction,
...extendedResults,
};
},
};
export default RootExtractor;