gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:05:16 25 4
gpt4 key购买 nike

我正在尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com