@d-zero/beholder 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/LICENSE +21 -0
- package/README.md +5 -0
- package/dist/debug.d.ts +6 -0
- package/dist/debug.js +6 -0
- package/dist/dom-evaluation.d.ts +24 -0
- package/dist/dom-evaluation.js +114 -0
- package/dist/events.d.ts +32 -0
- package/dist/events.js +15 -0
- package/dist/fetch-destination.d.ts +2 -0
- package/dist/fetch-destination.js +132 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/keyword-check.d.ts +1 -0
- package/dist/keyword-check.js +10 -0
- package/dist/net-timeout-error.d.ts +3 -0
- package/dist/net-timeout-error.js +3 -0
- package/dist/network.d.ts +2 -0
- package/dist/network.js +132 -0
- package/dist/scraper.d.ts +15 -0
- package/dist/scraper.js +678 -0
- package/dist/sub-process-runner.d.ts +12 -0
- package/dist/sub-process-runner.js +180 -0
- package/dist/sub-process.d.ts +1 -0
- package/dist/sub-process.js +67 -0
- package/dist/types.d.ts +271 -0
- package/dist/types.js +1 -0
- package/dist/utils.d.ts +5 -0
- package/dist/utils.js +142 -0
- package/package.json +34 -0
- package/src/debug.ts +7 -0
- package/src/dom-evaluation.ts +175 -0
- package/src/events.ts +21 -0
- package/src/fetch-destination.ts +160 -0
- package/src/index.ts +4 -0
- package/src/keyword-check.spec.ts +8 -0
- package/src/keyword-check.ts +12 -0
- package/src/net-timeout-error.ts +3 -0
- package/src/scraper.ts +733 -0
- package/src/sub-process-runner.ts +220 -0
- package/src/sub-process.ts +86 -0
- package/src/types.ts +341 -0
- package/src/utils.ts +171 -0
- package/tsconfig.json +15 -0
- package/tsconfig.tsbuildinfo +1 -0
package/package.json
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@d-zero/beholder",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "The tool for scraping and recording web pages",
|
|
5
|
+
"author": "D-ZERO",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"private": false,
|
|
8
|
+
"publishConfig": {
|
|
9
|
+
"access": "public"
|
|
10
|
+
},
|
|
11
|
+
"type": "module",
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"import": "./lib/index.js",
|
|
15
|
+
"types": "./lib/index.d.ts"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"scripts": {
|
|
19
|
+
"build": "tsc",
|
|
20
|
+
"clean": "tsc --build --clean"
|
|
21
|
+
},
|
|
22
|
+
"dependencies": {
|
|
23
|
+
"@d-zero/shared": "0.4.0",
|
|
24
|
+
"debug": "4.3.4",
|
|
25
|
+
"follow-redirects": "1.15.6",
|
|
26
|
+
"puppeteer": "22.9.0",
|
|
27
|
+
"typescript-fsa": "3.0.0"
|
|
28
|
+
},
|
|
29
|
+
"devDependencies": {
|
|
30
|
+
"@types/debug": "4.1.12",
|
|
31
|
+
"@types/follow-redirects": "1.14.4"
|
|
32
|
+
},
|
|
33
|
+
"gitHead": "acfefd8b20364c2aec1998517fc0b190fdc3b404"
|
|
34
|
+
}
|
package/src/debug.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import debug from 'debug';
|
|
2
|
+
|
|
3
|
+
export const log = debug('Beholder');
|
|
4
|
+
export const scraperLog = log.extend('Scraper');
|
|
5
|
+
export const resourceLog = scraperLog.extend('Resource');
|
|
6
|
+
export const domLog = scraperLog.extend('DOM');
|
|
7
|
+
export const domDetailsLog = domLog.extend('Details');
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import type { AnchorData, ImageElement, ParseURLOptions } from './types.js';
|
|
2
|
+
import type { ElementHandle, Page } from 'puppeteer';
|
|
3
|
+
|
|
4
|
+
import { domDetailsLog, domLog } from './debug.js';
|
|
5
|
+
import { parseUrl } from './utils.js';
|
|
6
|
+
|
|
7
|
+
const pid = `${process.pid}`;
|
|
8
|
+
const log = domLog.extend(pid);
|
|
9
|
+
const dLog = domDetailsLog.extend(pid);
|
|
10
|
+
|
|
11
|
+
export async function getProp<T>(
|
|
12
|
+
$el: ElementHandle<Element>,
|
|
13
|
+
propName: string,
|
|
14
|
+
fallback: T,
|
|
15
|
+
) {
|
|
16
|
+
return Promise.race([
|
|
17
|
+
_getProp($el, propName, fallback),
|
|
18
|
+
new Promise<T>((res) => setTimeout(() => res(fallback), 10 * 1000)),
|
|
19
|
+
]);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async function _getProp<T>($el: ElementHandle<Element>, propName: string, fallback: T) {
|
|
23
|
+
try {
|
|
24
|
+
const prop = await $el.getProperty(propName);
|
|
25
|
+
if (!prop) {
|
|
26
|
+
return fallback;
|
|
27
|
+
}
|
|
28
|
+
const value = (await prop.jsonValue()) as T;
|
|
29
|
+
return value;
|
|
30
|
+
} catch {
|
|
31
|
+
return fallback;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export async function getPropBySelector<T>(
|
|
36
|
+
page: Page,
|
|
37
|
+
selector: string,
|
|
38
|
+
propName: string,
|
|
39
|
+
fallback: T,
|
|
40
|
+
) {
|
|
41
|
+
const $el = await page.$(selector);
|
|
42
|
+
if (!$el) {
|
|
43
|
+
return fallback;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
return getProp($el, propName, fallback);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function getImageList(
|
|
50
|
+
page: Page,
|
|
51
|
+
viewportWidth: number,
|
|
52
|
+
): Promise<ImageElement[]> {
|
|
53
|
+
log('Getting images (Viewport: %dpx)', viewportWidth);
|
|
54
|
+
|
|
55
|
+
const $images = await page.$$('img');
|
|
56
|
+
const imageList: {
|
|
57
|
+
src: string;
|
|
58
|
+
currentSrc: string;
|
|
59
|
+
alt: string;
|
|
60
|
+
width: number;
|
|
61
|
+
height: number;
|
|
62
|
+
naturalWidth: number;
|
|
63
|
+
naturalHeight: number;
|
|
64
|
+
isLazy: boolean;
|
|
65
|
+
viewportWidth: number;
|
|
66
|
+
sourceCode: string;
|
|
67
|
+
}[] = [];
|
|
68
|
+
for (const $image of $images) {
|
|
69
|
+
const boundingBox = await $image.boundingBox();
|
|
70
|
+
const width = boundingBox?.width || 0;
|
|
71
|
+
const height = boundingBox?.height || 0;
|
|
72
|
+
const src = await getProp($image, 'src', '');
|
|
73
|
+
const currentSrc = await getProp($image, 'currentSrc', '');
|
|
74
|
+
const alt = await getProp($image, 'alt', '');
|
|
75
|
+
const naturalWidth = await getProp($image, 'naturalWidth', 0);
|
|
76
|
+
const naturalHeight = await getProp($image, 'naturalHeight', 0);
|
|
77
|
+
const loading = await getProp($image, 'loading', '');
|
|
78
|
+
const sourceCode = await getProp($image, 'outerHTML', '');
|
|
79
|
+
const isLazy = loading.toLowerCase().trim() === 'lazy';
|
|
80
|
+
imageList.push({
|
|
81
|
+
src,
|
|
82
|
+
currentSrc,
|
|
83
|
+
alt,
|
|
84
|
+
width,
|
|
85
|
+
height,
|
|
86
|
+
naturalWidth,
|
|
87
|
+
naturalHeight,
|
|
88
|
+
isLazy,
|
|
89
|
+
viewportWidth,
|
|
90
|
+
sourceCode,
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
log('Got %d images (Viewport: %dpx)', imageList.length, viewportWidth);
|
|
95
|
+
dLog(
|
|
96
|
+
'Images are: %O',
|
|
97
|
+
imageList.map((i) => i.src),
|
|
98
|
+
);
|
|
99
|
+
return imageList;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export async function getAnchorList(page: Page, options?: ParseURLOptions) {
|
|
103
|
+
log('Getting anchors');
|
|
104
|
+
|
|
105
|
+
const $anchors = await page.$$('a[href], area[href]');
|
|
106
|
+
const anchorList: AnchorData[] = [];
|
|
107
|
+
|
|
108
|
+
for (const $anchor of $anchors) {
|
|
109
|
+
const $href = await getProp($anchor, 'href', '');
|
|
110
|
+
const hrefVal = $href.toString();
|
|
111
|
+
const href = parseUrl(hrefVal, options);
|
|
112
|
+
if (!href || !href.isHTTP) {
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
const axNode = await page.accessibility.snapshot({ root: $anchor });
|
|
116
|
+
const textContent = await getProp($anchor, 'textContent', '');
|
|
117
|
+
const accessibleName = axNode ? axNode.name || '' : textContent.trim();
|
|
118
|
+
const link: AnchorData = {
|
|
119
|
+
href,
|
|
120
|
+
textContent: accessibleName,
|
|
121
|
+
};
|
|
122
|
+
anchorList.push(link);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
log('Got %d anchors', anchorList.length);
|
|
126
|
+
dLog(
|
|
127
|
+
'Anchors are: %O',
|
|
128
|
+
anchorList.map((a) => a.href.href),
|
|
129
|
+
);
|
|
130
|
+
return anchorList;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export async function getMeta(page: Page) {
|
|
134
|
+
log('Getting Meta');
|
|
135
|
+
|
|
136
|
+
const robotsVal = await getPropBySelector(page, 'meta[name="robots"]', 'content', '');
|
|
137
|
+
const robots = new Set(robotsVal.split(',').map((robot) => robot.trim().toLowerCase()));
|
|
138
|
+
const meta = {
|
|
139
|
+
title: await getPropBySelector(page, 'title', 'textContent', ''),
|
|
140
|
+
lang: await getPropBySelector(page, 'html', 'lang', ''),
|
|
141
|
+
description: await getPropBySelector(page, 'meta[name="description"]', 'content', ''),
|
|
142
|
+
keywords: await getPropBySelector(page, 'meta[name="keywords"]', 'content', ''),
|
|
143
|
+
noindex: robots.has('noindex'),
|
|
144
|
+
nofollow: robots.has('nofollow'),
|
|
145
|
+
noarchive: robots.has('noarchive'),
|
|
146
|
+
canonical: await getPropBySelector(page, 'link[rel="canonical"]', 'content', ''),
|
|
147
|
+
alternate: await getPropBySelector(page, 'link[rel="alternate"]', 'content', ''),
|
|
148
|
+
'og:type': await getPropBySelector(page, 'meta[property="og:type"]', 'content', ''),
|
|
149
|
+
'og:title': await getPropBySelector(page, 'meta[property="og:title"]', 'content', ''),
|
|
150
|
+
'og:site_name': await getPropBySelector(
|
|
151
|
+
page,
|
|
152
|
+
'meta[property="og:site_name"]',
|
|
153
|
+
'content',
|
|
154
|
+
'',
|
|
155
|
+
),
|
|
156
|
+
'og:description': await getPropBySelector(
|
|
157
|
+
page,
|
|
158
|
+
'meta[property="og:description"]',
|
|
159
|
+
'content',
|
|
160
|
+
'',
|
|
161
|
+
),
|
|
162
|
+
'og:url': await getPropBySelector(page, 'meta[property="og:url"]', 'content', ''),
|
|
163
|
+
'og:image': await getPropBySelector(page, 'meta[property="og:image"]', 'content', ''),
|
|
164
|
+
'twitter:card': await getPropBySelector(
|
|
165
|
+
page,
|
|
166
|
+
'meta[name="twitter:card"]',
|
|
167
|
+
'content',
|
|
168
|
+
'',
|
|
169
|
+
),
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
log('Got meta');
|
|
173
|
+
dLog('Meta data are: %O', meta);
|
|
174
|
+
return meta;
|
|
175
|
+
}
|
package/src/events.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { ScrapeEventTypes, SubProcessEventTypes } from './types.js';
|
|
2
|
+
|
|
3
|
+
import { actionCreatorFactory } from 'typescript-fsa';
|
|
4
|
+
|
|
5
|
+
const scraperEventCreator = actionCreatorFactory('@@scraper');
|
|
6
|
+
const subProcessEventCreator = actionCreatorFactory('@@sub-process');
|
|
7
|
+
|
|
8
|
+
export const subProcessEvent = {
|
|
9
|
+
start: subProcessEventCreator<SubProcessEventTypes['start']>('start'),
|
|
10
|
+
destroy: subProcessEventCreator<SubProcessEventTypes['destroy']>('destroy'),
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export const scraperEvent = {
|
|
14
|
+
ignoreAndSkip: scraperEventCreator<ScrapeEventTypes['ignoreAndSkip']>('ignoreAndSkip'),
|
|
15
|
+
resourceResponse:
|
|
16
|
+
scraperEventCreator<ScrapeEventTypes['resourceResponse']>('resourceResponse'),
|
|
17
|
+
scrapeEnd: scraperEventCreator<ScrapeEventTypes['scrapeEnd']>('scrapeEnd'),
|
|
18
|
+
destroyed: scraperEventCreator<ScrapeEventTypes['destroyed']>('destroyed'),
|
|
19
|
+
error: scraperEventCreator<ScrapeEventTypes['error']>('error'),
|
|
20
|
+
changePhase: scraperEventCreator<ScrapeEventTypes['changePhase']>('changePhase'),
|
|
21
|
+
};
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import type { PageData, ExURL } from './types.js';
|
|
2
|
+
import type { FollowResponse, RedirectableRequest } from 'follow-redirects';
|
|
3
|
+
import type { ClientRequest, IncomingMessage, RequestOptions } from 'node:http';
|
|
4
|
+
|
|
5
|
+
import { delay } from '@d-zero/shared/delay';
|
|
6
|
+
import redirects from 'follow-redirects';
|
|
7
|
+
|
|
8
|
+
import NetTimeoutError from './net-timeout-error.js';
|
|
9
|
+
|
|
10
|
+
const cacheMap = new Map<string, PageData | Error>();
|
|
11
|
+
|
|
12
|
+
export async function fetchDestination(
|
|
13
|
+
url: ExURL,
|
|
14
|
+
isExternal: boolean,
|
|
15
|
+
method = 'HEAD',
|
|
16
|
+
): Promise<PageData> {
|
|
17
|
+
if (cacheMap.has(url.withoutHash)) {
|
|
18
|
+
const cache = cacheMap.get(url.withoutHash)!;
|
|
19
|
+
if (cache instanceof Error) {
|
|
20
|
+
throw cache;
|
|
21
|
+
}
|
|
22
|
+
return cache;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const result = await Promise.race([
|
|
26
|
+
_fetchHead(url, isExternal, method).catch((error) => new Error(error)),
|
|
27
|
+
(async () => {
|
|
28
|
+
await delay(10 * 1000);
|
|
29
|
+
return new NetTimeoutError();
|
|
30
|
+
})(),
|
|
31
|
+
]);
|
|
32
|
+
|
|
33
|
+
cacheMap.set(url.withoutHash, result);
|
|
34
|
+
if (result instanceof Error) {
|
|
35
|
+
throw result;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
return result;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function _fetchHead(url: ExURL, isExternal: boolean, method: string) {
|
|
42
|
+
return new Promise<PageData>((resolve, reject) => {
|
|
43
|
+
const request: RequestOptions = {
|
|
44
|
+
protocol: url.protocol,
|
|
45
|
+
host: url.hostname,
|
|
46
|
+
path: url.pathname,
|
|
47
|
+
method,
|
|
48
|
+
headers: {
|
|
49
|
+
host: url.hostname,
|
|
50
|
+
Connection: 'keep-alive',
|
|
51
|
+
Pragma: 'no-cache',
|
|
52
|
+
'Cache-Control': 'no-cache',
|
|
53
|
+
'Upgrade-Insecure-Requests': 1,
|
|
54
|
+
// TODO: 'User-Agent': userAgent,
|
|
55
|
+
Accept:
|
|
56
|
+
'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', // cspell:disable-line
|
|
57
|
+
'Accept-Encoding': 'gzip, deflate',
|
|
58
|
+
'Accept-Language':
|
|
59
|
+
'ja,en;q=0.9,zh;q=0.8,en-US;q=0.7,pl;q=0.6,de;q=0.5,zh-CN;q=0.4,zh-TW;q=0.3,th;q=0.2,ko;q=0.1,fr;q=0.1',
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
if (url.username && url.password) {
|
|
64
|
+
request.auth = `${url.username}:${url.password}`;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
let req: RedirectableRequest<ClientRequest, IncomingMessage>;
|
|
68
|
+
const response = (res: IncomingMessage & FollowResponse) => {
|
|
69
|
+
res.on('data', () => {});
|
|
70
|
+
res.on('end', async () => {
|
|
71
|
+
const redirectPaths = res.redirects.map((r) => r.url);
|
|
72
|
+
const _contentLength = Number.parseInt(res.headers['content-length'] || '');
|
|
73
|
+
const contentLength = Number.isFinite(_contentLength) ? _contentLength : null;
|
|
74
|
+
let rep: PageData = {
|
|
75
|
+
url,
|
|
76
|
+
isTarget: !isExternal,
|
|
77
|
+
isExternal,
|
|
78
|
+
redirectPaths,
|
|
79
|
+
status: res.statusCode || 0,
|
|
80
|
+
statusText: res.statusMessage || '',
|
|
81
|
+
contentType: res.headers['content-type']?.split(';')[0] || null,
|
|
82
|
+
contentLength,
|
|
83
|
+
responseHeaders: res.headers,
|
|
84
|
+
meta: {
|
|
85
|
+
title: '',
|
|
86
|
+
},
|
|
87
|
+
imageList: [],
|
|
88
|
+
anchorList: [],
|
|
89
|
+
html: '',
|
|
90
|
+
isSkipped: false,
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
if (rep.status === 405) {
|
|
94
|
+
if (method === 'GET') {
|
|
95
|
+
reject(`Method Not Allowed: ${url} ${rep.statusText}`);
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
const rr = await fetchDestination(url, isExternal, 'GET').catch(
|
|
99
|
+
(error) => error,
|
|
100
|
+
);
|
|
101
|
+
if (rr) {
|
|
102
|
+
rep = rr;
|
|
103
|
+
} else {
|
|
104
|
+
reject(rr);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
if (rep.status === 501) {
|
|
109
|
+
if (method === 'GET') {
|
|
110
|
+
reject(`Method Not Implemented: ${url} ${rep.statusText}`);
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
await delay(5 * 1000);
|
|
114
|
+
const rr = await fetchDestination(url, isExternal, 'GET').catch(
|
|
115
|
+
(error) => error,
|
|
116
|
+
);
|
|
117
|
+
if (rr) {
|
|
118
|
+
rep = rr;
|
|
119
|
+
} else {
|
|
120
|
+
reject(rr);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (rep.status === 503) {
|
|
125
|
+
if (method === 'GET') {
|
|
126
|
+
reject(`Retrying failed: ${url} ${rep.statusText}`);
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
await delay(5 * 1000);
|
|
130
|
+
const rr = await fetchDestination(url, isExternal, 'GET').catch(
|
|
131
|
+
(error) => error,
|
|
132
|
+
);
|
|
133
|
+
if (rr) {
|
|
134
|
+
rep = rr;
|
|
135
|
+
} else {
|
|
136
|
+
reject(rr);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
resolve(rep);
|
|
141
|
+
});
|
|
142
|
+
};
|
|
143
|
+
if (url.protocol === 'https:') {
|
|
144
|
+
req = redirects.https.request(
|
|
145
|
+
{
|
|
146
|
+
...request,
|
|
147
|
+
rejectUnauthorized: false,
|
|
148
|
+
},
|
|
149
|
+
response,
|
|
150
|
+
);
|
|
151
|
+
} else {
|
|
152
|
+
req = redirects.http.request(request, response);
|
|
153
|
+
}
|
|
154
|
+
req.on('error', (error) => {
|
|
155
|
+
reject(error);
|
|
156
|
+
});
|
|
157
|
+
req.write('head');
|
|
158
|
+
req.end();
|
|
159
|
+
});
|
|
160
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { strToRegex } from '@d-zero/shared/str-to-regex';
|
|
2
|
+
|
|
3
|
+
export function keywordCheck(html: string, excludeKeywords: string[]) {
|
|
4
|
+
for (const keyword of excludeKeywords) {
|
|
5
|
+
const pattern = strToRegex(keyword);
|
|
6
|
+
if (pattern.test(html)) {
|
|
7
|
+
return keyword;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
return false;
|
|
12
|
+
}
|