javascript - 在node js中的for循环中下载图像

标签 javascript node.js linux web-scraping puppeteer

我正在尝试使用 puppeteer 和 Node js 从维基百科页面抓取图像,并且我成功获取了链接。我还可以从页面下载 1 张图像。但是每当我尝试循环调用我的下载函数时,它就会下载无效的图像。当我尝试抓取一张图像时,下载功能可以工作,但该功能无法循环工作。如果有人有任何建议请告诉我。提前致谢

这是我的代码

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


// download function

function download(uri, filename, callback) {
    request.head(uri, function(err, res, body) {
      request(uri)
      .pipe(fs.createWriteStream(filename))
      .on("close", callback);
   });
  }



let scrape = async ()=> {

    const browser = await puppeteer.launch({
        "headless": false
    });

    const page =await browser.newPage();        //opening new page

    await page.goto("https://www.wikipedia.org/");  // go to url

    const xpathselector = `//span[contains(text(), "Commons")]`;    //click on the commons buttons

    const commonlinks = await page.waitForXPath(xpathselector);     

    await page.waitFor(3000);

    await commonlinks.click();

    await page.waitFor(2000)

    const xpath = '//*[@id="mainpage-potd"]/div[1]/a/img';

    const imageXpath = await page.waitForXPath(xpath);
    const src = await imageXpath.evaluate(el => el.src)

    //downloading the 1st image from the page

    download(src, "image.jpg", function() {
        console.log("Image downloaded");
    });

    await page.waitFor(2000)

    //here we are going to another page

    const xpathselector1 ='//*[@id="mf-picture-picture"]/div[2]/ul/li[4]/a'     
    const previousPictture = await page.waitForXPath(xpathselector1);
    await page.waitFor(2000);
    previousPictture.click();

    await page.waitFor(1500);

    //getting urls of images

    const link_start = 0;
    const cue_card_links = await page.evaluate((selector) => {
        const anchors_node_list = document.querySelectorAll(selector);
        const anchors = [...anchors_node_list];
        return anchors.map(link => link.href);
      }, '#mw-content-text > div > table > tbody > tr > td > div > div > a');

      console.log("[#] Done getting links\n");

    for (let i = link_start; i < cue_card_links.length; i++) {
        let link = cue_card_links[i];

        //downloading all images from second page

        download(link, `image${i}.jpg`, function() {
            console.log("Image downloaded");
        });
    }



}

scrape();


最佳答案

下载应如下所示

// download function

function download(files, callback) {
    let index = 0;
    var data = setInterval(async () => {
        let i = index++
        if (i === files.length)
            clearInterval(data)
        else {
            request.head(files[i % files.length], function (err, res, body) {
                request(files[i % files.length])
                    .pipe(fs.createWriteStream(`image${i}.jpg`))
                    .on("close", callback);
            });
        }
    }, 4000);
}

并且去掉for循环调用的函数,for是sync fn,这样调用Fn

 download(cue_card_links, function () { console.log("Image downloaded"); });

关于javascript - 在node js中的for循环中下载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60428106/

相关文章:

javascript - Rails 5,Gmaps4Rails-设置

node.js - Yarn 不更新本地依赖

javascript - Mongoose 将两个查询合并为同一集合

python - 使用 Microsoft Visual Studio 附加到 Linux 进程?

javascript - 我们如何重新加载风 sails 控制台?

javascript - 正确从 javascript 关闭 iframe 并且不隐藏 iframe

javascript数组对象

javascript - Nodejs 使用 async/await 进行 Sequelize 事务而不回滚

mysql - 如何合并来自已发散的 mysql 模式的数据?

c - 为什么 inode 编号从 1 而不是 0 开始?