-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
440 lines (384 loc) · 12.6 KB
/
index.js
File metadata and controls
440 lines (384 loc) · 12.6 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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
const fs = require("fs");
const puppeteer = require("puppeteer");
const Hjson = require("hjson");
const readlineSync = require("readline-sync");
const {
cookies,
sleep,
sanitizeCookie,
findBookSourceByHost,
writeFile,
sanitizeFileName,
} = require("./utils");
const VERSION = "1.0.0";
// puppeteer config
const config = (function (filePath) {
let configFile = null;
if (!fs.existsSync(filePath)) {
console.log(">> 配置文件不存在, 创建默认配置文件...");
configFile = fs.readFileSync("./config.hjson.template", "utf8");
fs.writeFileSync(filePath, configFile, "utf8");
} else configFile = fs.readFileSync(filePath, "utf8");
return Hjson.parse(configFile);
})("./config.hjson");
const maxReloadCount = config.maxReloadCount;
const maxRetryCount = config.maxRetryCount;
const defaultSaveDir = config.defaultSaveDir;
const debug = config.debug;
const browserLaunchOptions = config.browserLaunchOptions;
const main = async () => {
console.log("\nNovel-Crawler 爬虫 v" + VERSION);
let url = readlineSync.question("请输入开始章节网址: ");
if (url == "") {
console.log("url为空,退出程序...");
return;
}
let startIndex = readlineSync.question("请输入起始章节(1): ");
let endIndex = readlineSync.question("请输入结束章节(2000): ");
if (startIndex == "") startIndex = 1;
if (endIndex == "") endIndex = 2000;
let dir = readlineSync.question(
`请输入小说存放资料夹(预设: ${defaultSaveDir})/书名: `
);
if (dir == "") {
dir = defaultSaveDir;
}
let mergeable;
if (readlineSync.keyInYN("请选择是否合并所有章节至单独文件?y/N(N)")) {
mergeable = true;
} else {
mergeable = false;
}
console.log("是否合并章节", mergeable);
let bookSourceName;
bookSourceName = readlineSync.question(
"请指定书源文件, 不指定则根据url自动匹配: "
);
console.log(`书源文件: ${"./bookSource/" + bookSourceName}`);
return await getBook(
url,
startIndex,
endIndex,
dir,
bookSourceName,
mergeable
);
};
/**
*
* @param {*} url
* @param {*} startIndex
* @param {*} endIndex
* @param {*} dir
* @param {*} bookSourceName
* @param {*} mergeable
* @returns
*/
const getBook = async (
url,
startIndex,
endIndex,
dir,
bookSourceName,
mergeable
) => {
console.log("获取书籍信息, 启动浏览器...");
const browser = await puppeteer.launch(browserLaunchOptions);
let bookSourcePath = null;
if (bookSourceName == "" || !bookSourceName) {
console.log("未指定书源文件,根据url自动匹配...");
try {
bookSourcePath = await deduceBookSourceFromUrl(url, "./bookSource");
} catch (error) {
console.log(">> 根据url自动匹配书源失败,退出程序... <<");
console.log(error);
return;
}
} else {
bookSourcePath = "./bookSource/" + bookSourceName;
}
console.log(">> 获取书源...");
console.log(">> 书源文件: " + bookSourcePath);
bookSource = Hjson.parse(fs.readFileSync(bookSourcePath, "utf8"));
console.log(
`>> 书源已确定: "${bookSource.bookSourceName}", "${bookSource.bookSourceUrl}"`
);
bookSource.getBookID = new Function(
bookSource.getBookID.arguments,
bookSource.getBookID.body
);
bookSource.getHomeUrl = new Function(
bookSource.getHomeUrl.arguments,
bookSource.getHomeUrl.body
);
bookSource.formatContentText = new Function(
bookSource.formatContentText.arguments,
bookSource.formatContentText.body
);
console.log(">> 书源初始化完成\n");
if (bookSource.note) console.log("书源信息: \n" + bookSource.note + "\n");
console.log("启动浏览器, 获取书籍信息...");
let bookInfo = await getBookInfo(browser, bookSource, url);
let bookname = bookInfo.bookname;
bookInfo.bookSourceVersion = bookSource.version;
bookInfo.crawlerVersion = `pyx/novel-crawler:v${VERSION}`;
console.log("书籍信息:\n" + JSON.stringify(bookInfo, null, 4));
if (dir[dir.length - 1] != "/") {
dir += "/";
}
if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) {
console.log(`\n >> 资料夹不存在,将会自动创建此目录: (${dir})`);
}
dir += bookname + "/";
console.log(`\n >> 小说将存储到: (${dir})`);
startIndex = parseInt(startIndex);
endIndex = parseInt(endIndex);
{
n = readlineSync.question("按任意键继续... 输入 n 退出");
if (n == "n") {
console.log("退出程序...");
browser.close();
return;
}
}
try {
fs.mkdirSync(`${dir}`, { recursive: true });
console.log(`创建目录"${dir}"成功。`);
} catch (error) {
if (error.code == "EEXIST") console.log("目录已存在,无需创建。");
else {
console.log("创建目录失败,未知错误... 打印错误信息:");
console.log(error);
}
}
if (startIndex <= 1) {
console.log("创建 000 介绍文件...");
writeFile(
`${dir}`,
`000.txt`,
JSON.stringify(bookInfo, null, 4),
` --> ${bookInfo.bookname} / 000 介绍文件 已储存\n`,
` #####! <-- 000 介绍文件写入错误 !!!!! 退出程序...######\n`
);
}
const page = await browser.newPage();
if (cookies) await setCookie(page, cookies, (verbose = debug));
console.log("标签页已启动, 开始爬取小说内容...");
let lastPageData = null;
for (pageNum = startIndex; pageNum <= endIndex; pageNum++) {
if (!url || url == "") {
console.error(
` #####! <-- ${dir} 第${pageNum}章 url为空 !!!!! 退出程序...######`
);
console.log(` url为: "${url}" index 为: ${pageNum}\n`);
break;
}
await page.goto(url).catch((err) => {
console.error(
` #####! <-- ${dir} 第${pageNum}章 访问失败 !!!!! 退出程序...######`
);
console.log(` url为: ${url} index 为: ${pageNum}\n`);
console.log(err);
return;
});
let contentPageData = null;
for (
let errCount = 0, reloadCount = 0;
errCount < maxRetryCount && reloadCount < maxReloadCount;
errCount++
) {
try {
await sleep(800 * errCount);
contentPageData = await page.evaluate((bookSource) => {
bookSource.getContent = new Function(
bookSource.getContent.arguments,
bookSource.getContent.body
);
return bookSource.getContent(document);
}, bookSource);
contentPageData.content = bookSource.formatContentText(
contentPageData.content
);
if (!contentPageData.title || contentPageData.title == "")
throw "title为空";
} catch (err) {
if (page.url() == bookInfo.homeUrl) {
console.log(
" #####! <-- 爬取完毕, 本页是目录页: home url. 退出程序...######"
);
return;
}
if (errCount >= maxRetryCount - 1) {
console.error(
` #####! <-- ${dir} 第${pageNum}章 爬取失敗 !!!!! 退出程序...######`
);
console.log("\n #####! <-- 爬取错误, contentPageData:");
console.log(contentPageData);
console.log(" #####! vvv-- 报错信息:");
console.log(err);
if (reloadCount < maxReloadCount - 1) {
console.log(
` #####! <-- 重新加载页面 ${
reloadCount + 2
}/${maxReloadCount} 次...`
);
reloadCount++;
errCount = -1;
continue;
}
console.log(
"可能是抵达最后一页, 但并未检测成功, 或是书源中的 getContent 函数报错, 请检查书源文件是否正确"
);
console.log(` url为: ${url} index 为: ${pageNum}`);
await browser.close();
return;
}
if (debug) {
console.log("\n #####! <-- 爬取错误, contentPageData:");
console.log(contentPageData);
console.log(" #####! vvv-- 报错信息:");
console.log(err);
}
console.error(
` #####! <-- ${dir} 第${pageNum}章 爬取失败,正在重试... ${
errCount + 1
}/10\n`
);
continue;
}
break;
}
if (!contentPageData) {
console.error(
` #####! <-- ${dir} 第${pageNum}章 爬取失败 !!!!! contentPageData 为空 退出程序...######`
);
console.log(` url为: ${url} index 为: ${pageNum}`);
console.log(
`上一个页面的数据为: ${JSON.stringify(lastPageData, null, 4)}`
);
break;
}
if (!contentPageData.content || !contentPageData.title) {
console.error(
` #####! <-- ${dir} 第${pageNum}章 爬取失敗 !!!!! contentPageData 小说正文/标题/下一页url爬取失败 退出程序...######`
);
console.log(` url为: ${url} index 为: ${pageNum}`);
console.log(
`contentPageData 为 ${JSON.stringify(contentPageData, null, 4)}`
);
console.log(
`上一个页面的数据为: ${JSON.stringify(lastPageData, null, 4)}`
);
}
if (lastPageData && contentPageData.title == lastPageData.title) {
console.log(
` <-- ! ${dir} 第${pageNum}章: ${contentPageData.title} - 于上一章 ${
pageNum - 1
} 标题相同, 写入同一个文件`
);
contentPageData.content =
lastPageData.content + "\n" + contentPageData.content;
pageNum--;
}
if (!mergeable) {
writeFile(
`${dir}`,
`${pageNum.toString().padStart(2, "0")} ${contentPageData.title}.txt`,
contentPageData.content,
` --> ${dir} 第${pageNum}章: ${contentPageData.title} 已储存\n`,
` #####! <-- ${dir}/ 第${pageNum}章: 写入错误或data为空 !!!!! 退出程序...######`
);
} else {
writeFile(
`${dir}`,
`${bookInfo.bookname}.txt`,
`${contentPageData.title}\n ${contentPageData.content.replaceAll(
" ",
"\n"
)}\n\n`,
` --> ${dir} 第${pageNum}章: ${contentPageData.title} 已儲存\n`,
` #####! <-- ${dir}/ 第${pageNum}章: 写入错误或data为空 !!!!! 退出程序...######`,
1,
"a+"
);
}
if (
!contentPageData.nextPageUrl ||
contentPageData.nextPageUrl == bookInfo.homeUrl
) {
console.log(
` #####! <-- 爬取完毕. 下一页url不存在或下一页是返回目录页\n 下一页url = "${contentPageData.nextPageUrl}" 退出程序...######`
);
break;
}
url = contentPageData.nextPageUrl;
lastPageData = contentPageData;
}
await browser.close();
console.log(" --- 任务完成 --- ");
};
/**
*
* @param {*} url
* @param {*} bookSourceDir
* @returns
*/
const deduceBookSourceFromUrl = async (url, bookSourceDir) => {
url = new URL(url);
let host = url.hostname.replace("www.", "");
let bookSource = findBookSourceByHost(bookSourceDir, host)[0];
if (!bookSource || bookSource == "") {
console.error(" #####! <-- 未找到匹配的小说源, 退出程序...######");
return null;
}
return bookSource;
};
const getBookInfo = async (browser, bookSource, chapterUrl) => {
console.log(" --- 正在获取小说信息 --- ");
let homeUrl = bookSource.getHomeUrl(bookSource.getBookID(chapterUrl));
console.log("书籍首页:", homeUrl);
const page = await browser.newPage();
await page.goto(homeUrl);
let data = null;
try {
data = await page.evaluate((bookSource) => {
bookSource.getBookInfo = new Function(
bookSource.getBookInfo.arguments,
bookSource.getBookInfo.body
);
return bookSource.getBookInfo(document);
}, bookSource);
} catch (err) {
console.error(` #####! <-- 000 介绍文件 爬取失敗,正在报错...`);
console.error(
` #####! <-- 可能是书源中的 getBookInfo 函数报错, 请检查书源文件是否正确`
);
console.error(` #####! <-- 接下来打印报错信息: \n\n`);
throw err;
}
data.homeUrl = homeUrl;
data.intro = convertToPlainText(data.intro);
page.close();
return data;
};
const convertToPlainText = (str) => {
try {
str = str.replace(/<br\s*\/?>/g, "\n");
str = str.replace(/ /g, "");
} catch (err) {
console.log(err);
}
return str;
};
const setCookie = async (page, cookies, verbose = false) => {
if (verbose) console.log("\n>> 正在设置cookie...");
for (let cookie of cookies) {
if (!cookie.value) {
if (verbose)
console.log(`>> 跳过cookie: ${JSON.stringify(cookie)} 因为value为空.`);
continue;
}
await page.setCookie(sanitizeCookie(cookie, verbose));
}
};
main();