javascript - 如何使用 Puppeteer 打印 HTML 文档?

标签 javascript node.js web-crawler google-chrome-devtools puppeteer

最近我开始使用 Puppeteer 来抓取网络。以下是从商城中提取特定产品名称的代码。

const puppeteer = require('puppeteer');

(async () => {

    const width = 1600, height = 1040;

    const option = { headless: false, slowMo: true, args: [`--window-size=${width},${height}`] };

    const browser = await puppeteer.launch(option);
    const page = await browser.newPage();
    const vp = {width: width, height: height};
    await page.setViewport(vp);

    const navigationPromise = page.waitForNavigation();

    await page.goto('https://shopping.naver.com/home/p/index.nhn');
    await navigationPromise;
    await page.waitFor(2000);

    const textBoxId = 'co_srh_input';
    await page.type('.' + textBoxId, '양말', {delay: 100});
    await page.keyboard.press('Enter');

    await page.waitFor(5000);
    await page.waitForSelector('div.info > a.tit');

    const stores = await page.evaluate(() => {
        const links = Array.from(document.querySelectorAll('div.info > a.tit'));
        return links.map(link => link.innerText).slice(0, 10)   // 10개 제품만 가져오기
    });

    console.log(stores);
    await browser.close();

})();

我有一个问题。如何将爬取结果输出到HTML文档(不使用数据库)?请使用示例代码进行解释。

最佳答案

我使用了在 blog.kowalczyk.info 上看到的内容

const puppeteer = require("puppeteer");
const fs = require("fs");

async function run() {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
    await page.goto("https://www.google.com/", { waitUntil: "networkidle2" });
    // hacky defensive move but I don't know a better way:
    // wait a bit so that the browser finishes executing JavaScript
    await page.waitFor(1 * 1000);
    const html = await page.content();
    fs.writeFileSync("index.html", html);
    await browser.close();
}

run();

关于javascript - 如何使用 Puppeteer 打印 HTML 文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53241203/

相关文章:

javascript - 如何在 md-select 内单击按钮时关闭 md-select?

javascript - CryptoJS 和 openssl_decrypt 不会产生相同的结果

javascript - 谷歌地图API错误: "initMap is not a function"

node.js - 使用 Jasmine 测试 Express/Passport 中间件——passport.authenticate 永远不会完成

javascript - Nodejs如何等待子进程退出或允许其响应

node.js - Nodejitsu + HTTPS

javascript - Bootstrap "tooltip"和 "popover"在表中添加额外的大小

python - Scrapy Python 设置用户代理

web-crawler - 创建机器人/爬虫

search-engine - 网络爬行和网络抓取有什么区别?