我如何使用 Google 的 Puppeteer 抓取整个网站,使其所有 CSS/JavaScript/媒体完好无损(而不仅仅是其 HTML)?在其他抓取作业上成功试用后,我想它应该可以。
但是翻遍了网上很多优秀的例子,并没有明显的方法可以做到这一点。我能找到的最接近的是调用
html_contents = await page.content()
并保存结果,但保存的是不含任何非 HTML 元素的副本。
有没有办法保存网页以供 Puppeteer 离线使用?
最佳答案
目前可以通过实验性 CDP 调用 'Page.captureSnapshot'
使用 MHTML格式:
'use strict';
const puppeteer = require('puppeteer');
const fs = require('fs');
(async function main() {
try {
const browser = await puppeteer.launch();
const [page] = await browser.pages();
await page.goto('https://en.wikipedia.org/wiki/MHTML');
const cdp = await page.target().createCDPSession();
const { data } = await cdp.send('Page.captureSnapshot', { format: 'mhtml' });
fs.writeFileSync('page.mhtml', data);
await browser.close();
} catch (err) {
console.error(err);
}
})();
关于javascript - Puppeteer:如何下载整个网页供离线使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54814323/