【问题标题】:Restart infinite when crawling results to JSON using Puppeteer使用 Puppeteer 将结果抓取到 JSON 时无限重启
【发布时间】:2019-04-21 19:11:13
【问题描述】:

我已成功使用 Puppeteer 进行爬网。下面是从商城中提取特定产品名称的代码。然而,我遇到了一个问题。

const express = require('express');
const puppeteer = require('puppeteer');
const fs = require('fs');

const app = express();

(async () => {

    const width = 1600, height = 1040;
    const option = { headless: true, slowMo: true, args: [`--window-size=${width},${height}`] };
    const browser = await puppeteer.launch(option);
    const page = await browser.newPage();

    await page.goto('https://search.shopping.naver.com/search/all.nhn?query=%EC%96%91%EB%A7%90&cat_id=&frm=NVSHATC');

    await page.waitFor(5000);
    await page.waitForSelector('ul.goods_list');
    await page.addScriptTag({url: 'https://code.jquery.com/jquery-3.2.1.min.js'});

    const naver = await page.evaluate(() => {
        const data = {
            "naver" : []
        };

        $('ul.goods_list > li._itemSection').each(function () {

            const title = $.trim($(this).find('div.info > a.tit').text());
            const price = $(this).find('div.info > .price .num').text();
            const image = $(this).find('div.img_area img').attr('src');

            data.naver.push({ title, price, image })

        });

        return data;
    });

    if (await write_file('example.json', JSON.stringify(naver)) === false) {
        console.error('Error: Unable to write stores to example.json');
    }

    await browser.close();

})();

const write_file = (file, data) => new Promise((resolve, reject) => {
    fs.writeFile(file, data, 'utf8', error => {
        if (error) {
            console.error(error);
            reject(false);
        } else {
            resolve(true);
        }
    });
});

app.listen(3000, () => console.log("Express!!!"));

我将抓取数据发送到 JSON 文件(example.json)。但我在无限重启时遇到了问题。我怎样才能让它只工作一次?

【问题讨论】:

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


    【解决方案1】:

    nodemon 正在重新启动您的进程,因为它检测到文件更改,即。你新写的文件。

    更新nodemon 配置以忽略.json 文件。

    npm

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-21
      • 2023-01-16
      • 2010-10-31
      • 1970-01-01
      • 1970-01-01
      • 2019-11-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多