-
Notifications
You must be signed in to change notification settings - Fork 0
/
nextjs.dev.ts
101 lines (83 loc) · 2.48 KB
/
nextjs.dev.ts
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
import { chromium } from "playwright";
import fs from "fs/promises";
import * as cheerio from "cheerio";
const run = async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto("https://nextjs.org/docs");
//get the nav element
const nav = await page.$("nav.styled-scrollbar");
if (!nav) {
throw new Error("nav element not found");
}
//get all the 'a' elements
const links = await nav.$$("a");
const urls = await Promise.all(
links.map(async (link) => {
return await link.getAttribute("href");
})
);
const wrapTextWithHtmlTags = (html: string) => {
const $ = cheerio.load(html);
$("h1").each((i, el) => {
const text = $(el).text();
$(el).text(`[titre principal]${text}[/titre principal]`);
});
$("h2").each((i, el) => {
const text = $(el).text();
$(el).text(`[sous-titre]${text}[/sous-titre]`);
});
$("p").each((i, el) => {
const text = $(el).text();
$(el).text(`[paragraphe]${text}[/paragraphe]`);
});
$("a").each((i, el) => {
const text = $(el).text();
const href = $(el).attr("href");
$(el).replaceWith(`[lien href="${href}"]${text}[/lien]`);
});
$("table").each((i, el) => {
const text = $(el).text();
$(el).text(`[tableau]${text}[/tableau]`);
});
$("code").each((i, el) => {
const text = $(el).text();
$(el).text(`[code]${text}[/code]`);
});
$("img").each((i, el) => {
const altText = $(el).attr("alt") || "Image sans texte alternatif";
$(el).replaceWith(`[image]${altText}[/image]`);
});
const text = $.text();
return text;
};
let totalSave = 0;
for (const url of urls) {
totalSave++;
if (!url) {
continue;
}
console.log("👀 visiting url:", url);
await page.goto(`https://nextjs.org/${url}`);
const html = await page.$eval(
"div.prose.prose-vercel",
(el) => el.innerHTML
);
if (!html) {
continue;
}
const text = wrapTextWithHtmlTags(html);
const cleanedText = text
.split("\n")
.filter((line) => line.trim().length > 0)
.join("\n");
const fileName =
url.replace(/^https?:\/\//, "").replace(/[^a-z0-9\-]/gi, "_") + ".txt";
const filePath = `./data/nextjs/${fileName}`;
console.log("🚀 Save " + filePath + " " + totalSave + "/" + urls.length);
fs.writeFile(filePath, cleanedText, "utf8");
}
console.log("end");
await browser.close();
};
run();