我正在使用 Puppeteer 抓取一些資料,需要在相對較短的時間內訪問很多頁面。經過觀察,我注意到這非常低效,因為我只對標記檔案中的資料感興趣,而包含所有影像、字體等的整個頁面非常慢。因此,如果有一種方法可以跳過其他內容型別并使 Puppeteer 僅回傳 HTML 檔案內容,那就太好了。這是我的代碼:
const browser = await puppeteer.launch({ headless: false });
const page = await browser.newPage();
const helperFile = fs.readFileSync("dist/app/scripts/helpers.js", "utf8");
await page.evaluateOnNewDocument(helperFile);
await login(page);
await postLogin(page);
await crawl(page); // this function is gonna call a lot of page.goTo(...)
await browser.close();
uj5u.com熱心網友回復:
您可以攔截來自 Puppeteer 的所有請求,只允許回傳檔案的請求continue()并丟棄其余請求。
我還決定包含該script型別,因為 JS 代碼可能會修改初始 DOM 樹(類似于appendChild(node)),如果您將 SPA 與現代韌體/庫(如 React)一起使用,其中服務器僅回傳幾個 JS 包,則尤其如此在客戶端生成 HTML。該script和fetch型別存在的情況下,JS代碼,使額外的請求到服務器,以獲得更多的資料,并更新DOM樹。
import puppeteer, { Page, PageEmittedEvents } from "puppeteer";
const htmlOnly = async (page: Page) => {
await page.setRequestInterception(true); // enable request interception
page.on(PageEmittedEvents.Request, (req) => {
if (!["document", "xhr", "fetch", "script"].includes(req.resourceType())) {
return req.abort();
}
req.continue();
});
};
const browser = await puppeteer.launch({ headless: false });
const page = await browser.newPage();
await htmlOnly(page);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/371503.html
