novel-full-scraper 1.0.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/LICENSE +21 -0
- package/README.md +32 -0
- package/bin/cli.js +49 -0
- package/package.json +51 -0
- package/src/epub.js +54 -0
- package/src/index.js +177 -0
- package/src/scraper.js +151 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Emmanuel Zvinoera
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# novel-full-scraper
|
|
2
|
+
|
|
3
|
+
Interactive CLI to scrape web novels from novelfull.com and export them as EPUB files.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install -g novel-full-scraper
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
novel-scrape
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Follow the interactive prompts to search for a novel, choose a chapter range,
|
|
18
|
+
and save the result as an EPUB.
|
|
19
|
+
|
|
20
|
+
## Requirements
|
|
21
|
+
|
|
22
|
+
- Node.js 18 or later
|
|
23
|
+
|
|
24
|
+
## Disclaimer
|
|
25
|
+
|
|
26
|
+
For personal and educational use only. Please respect novelfull.com's Terms of
|
|
27
|
+
Service and support the original authors by purchasing official releases when
|
|
28
|
+
available.
|
|
29
|
+
|
|
30
|
+
## License
|
|
31
|
+
|
|
32
|
+
MIT
|
package/bin/cli.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { main } from '../src/index.js';
|
|
3
|
+
|
|
4
|
+
// Handle --help and --version without loading the whole app
|
|
5
|
+
const args = process.argv.slice(2);
|
|
6
|
+
|
|
7
|
+
if (args.includes('--version') || args.includes('-v')) {
|
|
8
|
+
const { readFileSync } = await import('node:fs');
|
|
9
|
+
const { fileURLToPath } = await import('node:url');
|
|
10
|
+
const { dirname, join } = await import('node:path');
|
|
11
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
12
|
+
const pkg = JSON.parse(
|
|
13
|
+
readFileSync(join(__dirname, '..', 'package.json'), 'utf8')
|
|
14
|
+
);
|
|
15
|
+
console.log(pkg.version);
|
|
16
|
+
process.exit(0);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
if (args.includes('--help') || args.includes('-h')) {
|
|
20
|
+
console.log(`
|
|
21
|
+
novel-scrape — Interactive CLI to scrape web novels into EPUB files.
|
|
22
|
+
|
|
23
|
+
Usage:
|
|
24
|
+
novel-scrape Launch interactive prompts
|
|
25
|
+
|
|
26
|
+
Options:
|
|
27
|
+
-h, --help Show this help message
|
|
28
|
+
-v, --version Show version number
|
|
29
|
+
|
|
30
|
+
Example:
|
|
31
|
+
$ novel-scrape
|
|
32
|
+
|
|
33
|
+
Disclaimer:
|
|
34
|
+
For personal/educational use only. Please respect novelfull.com's
|
|
35
|
+
Terms of Service and support the original authors of the novels.
|
|
36
|
+
`);
|
|
37
|
+
process.exit(0);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Handle Ctrl+C cleanly
|
|
41
|
+
process.on('SIGINT', () => {
|
|
42
|
+
console.log('\nInterrupted. Exiting...');
|
|
43
|
+
process.exit(130);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
main().catch((err) => {
|
|
47
|
+
console.error('\n❌ Unexpected error:', err.message);
|
|
48
|
+
process.exit(1);
|
|
49
|
+
});
|
package/package.json
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "novel-full-scraper",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Interactive CLI to scrape web novels from novelfull.com and export them as EPUB files.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "src/index.js",
|
|
7
|
+
"bin": {
|
|
8
|
+
"novel-scrape": "./bin/cli.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"bin",
|
|
12
|
+
"src",
|
|
13
|
+
"README.md",
|
|
14
|
+
"LICENSE"
|
|
15
|
+
],
|
|
16
|
+
"engines": {
|
|
17
|
+
"node": ">=18"
|
|
18
|
+
},
|
|
19
|
+
"scripts": {
|
|
20
|
+
"start": "node bin/cli.js",
|
|
21
|
+
"test": "echo \"Error: no test specified\" && exit 1"
|
|
22
|
+
},
|
|
23
|
+
"keywords": [
|
|
24
|
+
"cli",
|
|
25
|
+
"epub",
|
|
26
|
+
"scraper",
|
|
27
|
+
"novel",
|
|
28
|
+
"web-novel",
|
|
29
|
+
"novelfull",
|
|
30
|
+
"puppeteer",
|
|
31
|
+
"ebook"
|
|
32
|
+
],
|
|
33
|
+
"author": "Your Name <your.email@example.com>",
|
|
34
|
+
"license": "MIT",
|
|
35
|
+
"repository": {
|
|
36
|
+
"type": "git",
|
|
37
|
+
"url": "git+https://github.com/YOUR_USERNAME/novel-full-scraper.git"
|
|
38
|
+
},
|
|
39
|
+
"bugs": {
|
|
40
|
+
"url": "https://github.com/YOUR_USERNAME/novel-full-scraper/issues"
|
|
41
|
+
},
|
|
42
|
+
"homepage": "https://github.com/YOUR_USERNAME/novel-full-scraper#readme",
|
|
43
|
+
"dependencies": {
|
|
44
|
+
"@clack/prompts": "^1.8.1",
|
|
45
|
+
"epub-gen-memory": "^1.1.2",
|
|
46
|
+
"picocolors": "^1.1.1",
|
|
47
|
+
"puppeteer": "^25.11.0",
|
|
48
|
+
"puppeteer-extra": "^3.3.6",
|
|
49
|
+
"puppeteer-extra-plugin-stealth": "^2.11.2"
|
|
50
|
+
}
|
|
51
|
+
}
|
package/src/epub.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import pkg from 'epub-gen-memory';
|
|
4
|
+
|
|
5
|
+
// epub-gen-memory ships as CJS; handle both interop shapes.
|
|
6
|
+
const epub = pkg.default || pkg;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Generate an EPUB file from an array of chapters.
|
|
10
|
+
*
|
|
11
|
+
* @param {Array<{title: string, content: string}>} chapters
|
|
12
|
+
* @param {object} meta
|
|
13
|
+
* @param {string} meta.fileName Output file name (no extension)
|
|
14
|
+
* @param {string} meta.bookTitle
|
|
15
|
+
* @param {string} meta.filePath Absolute output directory
|
|
16
|
+
* @param {string} [meta.author]
|
|
17
|
+
* @returns {Promise<string>} Absolute path to the written file
|
|
18
|
+
*/
|
|
19
|
+
export async function createAndSaveEpub(chapters, meta) {
|
|
20
|
+
const {
|
|
21
|
+
fileName,
|
|
22
|
+
bookTitle,
|
|
23
|
+
filePath,
|
|
24
|
+
author = 'Unknown',
|
|
25
|
+
publisher = 'novel-full-scraper',
|
|
26
|
+
} = meta;
|
|
27
|
+
|
|
28
|
+
if (!chapters?.length) {
|
|
29
|
+
throw new Error('No chapters provided to createAndSaveEpub.');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const options = {
|
|
33
|
+
title: bookTitle,
|
|
34
|
+
author,
|
|
35
|
+
publisher,
|
|
36
|
+
// intentionally no `cover` — empty string trips the library
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const chaptersData = chapters.map((ch) => ({
|
|
40
|
+
title: ch.title || 'Untitled Chapter',
|
|
41
|
+
content: ch.content ? ch.content.toString() : '<p>No content available.</p>',
|
|
42
|
+
}));
|
|
43
|
+
|
|
44
|
+
const epubBuffer = await epub(options, chaptersData);
|
|
45
|
+
|
|
46
|
+
if (!fs.existsSync(filePath)) {
|
|
47
|
+
fs.mkdirSync(filePath, { recursive: true });
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const finalPath = path.join(filePath, `${fileName}.epub`);
|
|
51
|
+
fs.writeFileSync(finalPath, epubBuffer);
|
|
52
|
+
|
|
53
|
+
return finalPath;
|
|
54
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
4
|
+
import * as p from '@clack/prompts';
|
|
5
|
+
import color from 'picocolors';
|
|
6
|
+
|
|
7
|
+
import {
|
|
8
|
+
launchBrowser,
|
|
9
|
+
getSearchResults,
|
|
10
|
+
getChapterLinks,
|
|
11
|
+
scrapeChaptersBatched,
|
|
12
|
+
} from './scraper.js';
|
|
13
|
+
import { createAndSaveEpub } from './epub.js';
|
|
14
|
+
|
|
15
|
+
export async function main() {
|
|
16
|
+
console.clear();
|
|
17
|
+
await sleep(500);
|
|
18
|
+
|
|
19
|
+
p.intro(`${color.bgCyan(color.black(' novel-full-scraper '))}`);
|
|
20
|
+
|
|
21
|
+
const browser = await launchBrowser();
|
|
22
|
+
let links = [];
|
|
23
|
+
|
|
24
|
+
try {
|
|
25
|
+
const project = await p.group(
|
|
26
|
+
{
|
|
27
|
+
search: () =>
|
|
28
|
+
p.text({
|
|
29
|
+
message: 'What novel do you want to search?',
|
|
30
|
+
placeholder: 'Lord of the Mysteries',
|
|
31
|
+
validate: (v) =>
|
|
32
|
+
v.trim().length < 2
|
|
33
|
+
? 'Please enter at least 2 characters.'
|
|
34
|
+
: undefined,
|
|
35
|
+
}),
|
|
36
|
+
|
|
37
|
+
novel: async ({ results }) => {
|
|
38
|
+
const s = p.spinner();
|
|
39
|
+
s.start(`Searching for "${results.search}"...`);
|
|
40
|
+
const options = await getSearchResults(results.search, browser);
|
|
41
|
+
s.stop(`Found ${options.length} match(es).`);
|
|
42
|
+
|
|
43
|
+
if (options.length === 0) {
|
|
44
|
+
p.cancel('No novels found. Try a different keyword.');
|
|
45
|
+
process.exit(0);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
return p.select({ message: 'Choose a novel', options });
|
|
49
|
+
},
|
|
50
|
+
|
|
51
|
+
start: async ({ results }) => {
|
|
52
|
+
const s = p.spinner();
|
|
53
|
+
s.start(`Fetching chapter list...`);
|
|
54
|
+
links = await getChapterLinks(results.novel, browser);
|
|
55
|
+
s.stop(`Found ${links.length} chapters.`);
|
|
56
|
+
|
|
57
|
+
if (links.length === 0) {
|
|
58
|
+
p.cancel('No chapters found for this novel.');
|
|
59
|
+
process.exit(0);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
return p.text({
|
|
63
|
+
message: 'Start chapter index',
|
|
64
|
+
placeholder: '1',
|
|
65
|
+
validate(value) {
|
|
66
|
+
const num = parseInt(value, 10);
|
|
67
|
+
if (isNaN(num) || num < 1 || num > links.length) {
|
|
68
|
+
return `Enter a number between 1 and ${links.length}`;
|
|
69
|
+
}
|
|
70
|
+
},
|
|
71
|
+
});
|
|
72
|
+
},
|
|
73
|
+
|
|
74
|
+
end: ({ results }) => {
|
|
75
|
+
const startNum = parseInt(results.start, 10);
|
|
76
|
+
return p.text({
|
|
77
|
+
message: 'End chapter index',
|
|
78
|
+
placeholder: `${links.length}`,
|
|
79
|
+
validate(value) {
|
|
80
|
+
const num = parseInt(value, 10);
|
|
81
|
+
if (isNaN(num) || num < startNum || num > links.length) {
|
|
82
|
+
return `Enter a number between ${startNum} and ${links.length}`;
|
|
83
|
+
}
|
|
84
|
+
},
|
|
85
|
+
});
|
|
86
|
+
},
|
|
87
|
+
|
|
88
|
+
filepath: () =>
|
|
89
|
+
p.text({
|
|
90
|
+
message: 'Where to save the file (absolute path)',
|
|
91
|
+
placeholder:
|
|
92
|
+
process.platform === 'win32'
|
|
93
|
+
? 'C:\\Users\\Name\\Documents\\Books'
|
|
94
|
+
: '/Users/Name/Documents/Books',
|
|
95
|
+
validate(value) {
|
|
96
|
+
const cleaned = value.trim();
|
|
97
|
+
if (!cleaned) return 'Path cannot be empty.';
|
|
98
|
+
if (!path.isAbsolute(cleaned))
|
|
99
|
+
return 'Path must be absolute.';
|
|
100
|
+
if (
|
|
101
|
+
process.platform !== 'win32' &&
|
|
102
|
+
/[<>:"|?*]/.test(cleaned)
|
|
103
|
+
) {
|
|
104
|
+
return 'Path contains invalid characters.';
|
|
105
|
+
}
|
|
106
|
+
},
|
|
107
|
+
}),
|
|
108
|
+
|
|
109
|
+
filename: () =>
|
|
110
|
+
p.text({
|
|
111
|
+
message: 'File name (no extension)',
|
|
112
|
+
placeholder: 'lord_of_the_mysteries',
|
|
113
|
+
validate(value) {
|
|
114
|
+
const cleaned = value.trim();
|
|
115
|
+
if (cleaned.length <= 3)
|
|
116
|
+
return 'File name must be more than 3 characters.';
|
|
117
|
+
if (/[\\/:*?"<>|]/.test(cleaned))
|
|
118
|
+
return 'File name contains invalid characters.';
|
|
119
|
+
},
|
|
120
|
+
}),
|
|
121
|
+
},
|
|
122
|
+
{
|
|
123
|
+
onCancel: () => {
|
|
124
|
+
p.cancel('Operation cancelled.');
|
|
125
|
+
browser.close();
|
|
126
|
+
process.exit(0);
|
|
127
|
+
},
|
|
128
|
+
}
|
|
129
|
+
);
|
|
130
|
+
|
|
131
|
+
// ── Scrape ──
|
|
132
|
+
const startIdx = parseInt(project.start, 10) - 1;
|
|
133
|
+
const endIdx = parseInt(project.end, 10);
|
|
134
|
+
const targetLinks = links.slice(startIdx, endIdx);
|
|
135
|
+
|
|
136
|
+
const scrapeSpinner = p.spinner();
|
|
137
|
+
scrapeSpinner.start(`Scraping ${targetLinks.length} chapters...`);
|
|
138
|
+
|
|
139
|
+
const chapters = await scrapeChaptersBatched(targetLinks, browser, {
|
|
140
|
+
batchSize: 5,
|
|
141
|
+
delayMs: 1000,
|
|
142
|
+
onBatch: (from, to, total) => {
|
|
143
|
+
scrapeSpinner.message(
|
|
144
|
+
`Scraping chapters ${from + 1}–${to} of ${total}...`
|
|
145
|
+
);
|
|
146
|
+
},
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
scrapeSpinner.stop(`Compiled ${chapters.length} chapters.`);
|
|
150
|
+
|
|
151
|
+
// ── Build EPUB ──
|
|
152
|
+
const targetDirectory = project.filepath.trim();
|
|
153
|
+
if (!fs.existsSync(targetDirectory)) {
|
|
154
|
+
fs.mkdirSync(targetDirectory, { recursive: true });
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const epubSpinner = p.spinner();
|
|
158
|
+
epubSpinner.start('Generating EPUB file...');
|
|
159
|
+
|
|
160
|
+
try {
|
|
161
|
+
const finalPath = await createAndSaveEpub(chapters, {
|
|
162
|
+
fileName: project.filename,
|
|
163
|
+
bookTitle: project.novel,
|
|
164
|
+
filePath: targetDirectory,
|
|
165
|
+
});
|
|
166
|
+
epubSpinner.stop(`📦 EPUB saved to: ${finalPath}`);
|
|
167
|
+
} catch (err) {
|
|
168
|
+
epubSpinner.stop('❌ Failed to create EPUB.');
|
|
169
|
+
p.cancel(`Error building book: ${err.message}`);
|
|
170
|
+
process.exit(1);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
p.outro(`${color.green('Done!')} Thanks for using novel-full-scraper.`);
|
|
174
|
+
} finally {
|
|
175
|
+
await browser.close();
|
|
176
|
+
}
|
|
177
|
+
}
|
package/src/scraper.js
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import puppeteer from 'puppeteer-extra';
|
|
2
|
+
import StealthPlugin from 'puppeteer-extra-plugin-stealth';
|
|
3
|
+
|
|
4
|
+
puppeteer.use(StealthPlugin());
|
|
5
|
+
|
|
6
|
+
const BASE_URL = 'https://novelfull.com';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Launch a single reusable browser. Callers must close it.
|
|
10
|
+
*/
|
|
11
|
+
export async function launchBrowser() {
|
|
12
|
+
return puppeteer.launch({ headless: true });
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Search for novels by keyword. Returns array of { label, value }
|
|
17
|
+
* ready to feed to @clack/prompts' select().
|
|
18
|
+
*/
|
|
19
|
+
export async function getSearchResults(novel, browser) {
|
|
20
|
+
const page = await browser.newPage();
|
|
21
|
+
try {
|
|
22
|
+
const query = novel.replace(/ /g, '+');
|
|
23
|
+
const url = `${BASE_URL}/search?keyword=${query}`;
|
|
24
|
+
|
|
25
|
+
await page.goto(url, { waitUntil: 'domcontentloaded' });
|
|
26
|
+
await page.waitForSelector('.list-truyen .row', { timeout: 5000 });
|
|
27
|
+
|
|
28
|
+
return await page.evaluate(() => {
|
|
29
|
+
const linkElements = document.querySelectorAll('h3.truyen-title a');
|
|
30
|
+
return Array.from(linkElements).map((book) => ({
|
|
31
|
+
label: book.textContent.trim(),
|
|
32
|
+
value: book.getAttribute('href'),
|
|
33
|
+
}));
|
|
34
|
+
});
|
|
35
|
+
} finally {
|
|
36
|
+
await page.close();
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Scrape every chapter link across all paginated pages of a novel.
|
|
42
|
+
*/
|
|
43
|
+
export async function getChapterLinks(relativePath, browser) {
|
|
44
|
+
const page = await browser.newPage();
|
|
45
|
+
try {
|
|
46
|
+
const url = `${BASE_URL}${relativePath}`;
|
|
47
|
+
await page.goto(url, { waitUntil: 'domcontentloaded' });
|
|
48
|
+
await page.waitForSelector('.l-chapter', { timeout: 5000 });
|
|
49
|
+
|
|
50
|
+
const latest = await page.evaluate(() => {
|
|
51
|
+
const latestChapter = document.querySelector('.l-chapters li a');
|
|
52
|
+
const num = latestChapter.getAttribute('title').split(' ')[1];
|
|
53
|
+
return parseInt(num, 10);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
const CHAPTERS_PER_PAGE = 50;
|
|
57
|
+
const maxPages = Math.ceil(latest / CHAPTERS_PER_PAGE);
|
|
58
|
+
const allChapterLinks = [];
|
|
59
|
+
|
|
60
|
+
for (let currentPage = 1; currentPage <= maxPages; currentPage++) {
|
|
61
|
+
const pageUrl = `${BASE_URL}${relativePath}?page=${currentPage}`;
|
|
62
|
+
await page.goto(pageUrl, { waitUntil: 'domcontentloaded' });
|
|
63
|
+
await page.waitForSelector('.l-chapter', { timeout: 5000 });
|
|
64
|
+
|
|
65
|
+
const chapterLinks = await page.evaluate(() => {
|
|
66
|
+
const chapters = document.querySelectorAll('ul.list-chapter li a');
|
|
67
|
+
return Array.from(chapters).map((c) => c.getAttribute('href'));
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
allChapterLinks.push(...chapterLinks);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
return allChapterLinks;
|
|
74
|
+
} finally {
|
|
75
|
+
await page.close();
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Fetch the HTML content of a single chapter. Returns { title, content }.
|
|
81
|
+
*/
|
|
82
|
+
export async function getChapterContents(relativeUrl, browser) {
|
|
83
|
+
const page = await browser.newPage();
|
|
84
|
+
try {
|
|
85
|
+
await page.goto(`${BASE_URL}${relativeUrl}`, {
|
|
86
|
+
waitUntil: 'domcontentloaded',
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
const chapterContents = await page.evaluate(() => {
|
|
90
|
+
const container = document.querySelector('.chapter-c');
|
|
91
|
+
if (!container) return '';
|
|
92
|
+
|
|
93
|
+
// Strip ad blocks
|
|
94
|
+
container
|
|
95
|
+
.querySelectorAll('div[align="center"], script, ins')
|
|
96
|
+
.forEach((el) => el.remove());
|
|
97
|
+
|
|
98
|
+
return container.innerHTML;
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
const filename = relativeUrl.split('/').pop().replace('.html', '');
|
|
102
|
+
const parsedTitle = filename
|
|
103
|
+
.split('-')
|
|
104
|
+
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
|
|
105
|
+
.join(' ');
|
|
106
|
+
|
|
107
|
+
return {
|
|
108
|
+
title: parsedTitle,
|
|
109
|
+
content: chapterContents || '<p>No content available.</p>',
|
|
110
|
+
};
|
|
111
|
+
} finally {
|
|
112
|
+
await page.close();
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Scrape a range of chapters in batches with delay between batches.
|
|
118
|
+
*/
|
|
119
|
+
export async function scrapeChaptersBatched(
|
|
120
|
+
links,
|
|
121
|
+
browser,
|
|
122
|
+
{ batchSize = 5, delayMs = 1000, onBatch = () => {} } = {}
|
|
123
|
+
) {
|
|
124
|
+
const results = [];
|
|
125
|
+
|
|
126
|
+
for (let i = 0; i < links.length; i += batchSize) {
|
|
127
|
+
const batch = links.slice(i, i + batchSize);
|
|
128
|
+
onBatch(i, Math.min(i + batchSize, links.length), links.length);
|
|
129
|
+
|
|
130
|
+
const batchResults = await Promise.all(
|
|
131
|
+
batch.map(async (link) => {
|
|
132
|
+
try {
|
|
133
|
+
return await getChapterContents(link, browser);
|
|
134
|
+
} catch (err) {
|
|
135
|
+
return {
|
|
136
|
+
title: `Failed: ${link}`,
|
|
137
|
+
content: `<p>Failed to fetch: ${err.message}</p>`,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
})
|
|
141
|
+
);
|
|
142
|
+
|
|
143
|
+
results.push(...batchResults);
|
|
144
|
+
|
|
145
|
+
if (i + batchSize < links.length) {
|
|
146
|
+
await new Promise((r) => setTimeout(r, delayMs));
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
return results;
|
|
151
|
+
}
|