我正在尝试将网站下载为静态,我的意思是没有 JS,只有 HTML 和 CSS。
我已经尝试了很多方法,但仍然存在一些关于 CSS 和 图像 的问题。
一个片段
const puppeteer = require('puppeteer');
const {URL} = require('url');
const fse = require('fs-extra');
const path = require('path');
(async (urlToFetch) => {
const browser = await puppeteer.launch({
headless: true,
slowMo: 100
});
const page = await browser.newPage();
await page.setRequestInterception(true);
page.on("request", request => {
if (request.resourceType() === "script") {
request.abort()
} else {
request.continue()
}
})
page.on('response', async (response) => {
const url = new URL(response.url());
let filePath = path.resolve(`./output${url.pathname}`);
if(path.extname(url.pathname).trim() === '') {
filePath = `${filePath}/index.html`;
}
await fse.outputFile(filePath, await response.buffer());
console.log(`File ${filePath} is written successfully`);
});
await page.goto(urlToFetch, {
waitUntil: 'networkidle2'
})
setTimeout(async () => {
await browser.close();
}, 60000 * 4)
})('https://stackoverflow.com/');
我尝试过使用
content = await page.content();
fs.writeFileSync('index.html', content, { encoding: 'utf-8' });
此外,我使用 CDPSession
下载它。
我已经尝试过使用website-scraper
那么,解决方案的最佳方法是什么,我提供一个网站链接,然后将其下载为静态网站。
最佳答案
尝试使用这个https://www.npmjs.com/package/website-scraper
它将把网站保存到本地目录
关于javascript - 使用 puppeteer 在本地下载网站,无需 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67559777/