这是我第一次在这里发帖,所以我希望我发帖的方式是正确的--先谢谢你的耐心!
我正在使用Puppeteer从下面的网站上刮取图片来源。
使用Puppeteer中的page.evaluate(),我可以使用下面的代码正确地刮取一个图像源。
const puppeteer = require("puppeteer");
var imgQuery, imgQuerySource;
(async () => {
const browser = await puppeteer.launch({ headless: true });
const page = await browser.newPage();
const navigationPromise = page.waitForNavigation({ waitUntil: "load" });
await page.goto("https://www.palaceskateboards.com/range/summer-2020/", { waitUntil: "load" });
await navigationPromise;
var imageSource = await page.evaluate(() => {
imgQuery = document.querySelectorAll("img");
imgQuerySource = imgQuery[0].getAttribute("src");
return imgQuerySource;
});
console.log(imageSource)
await page.close();
await browser.close();
})();
它正确地返回了控制台中的第一个图像源。
https://images.palaceskateboards.com/wp-content/uploads/2020/05/Palace-2020-spring-ark-air-grn-8675-300x210.jpg
成功!然而我很难将刮取所有链接的长度为imageSource。我已经尝试了所有我能找到的解决方案,包括引入一个for循环与.push(),也使用其他方法,如page.eval$(),但我无法得到它的结果。有谁能告诉我正确的方向,让我有效地将所有108个值刮取并放入一个数组中?谢谢你的时间!这是我第一次在这里发帖。
document.querySelectorAll
返回一个NodeList,所以我把它解构为一个数组,这样就可以让 .map
是可用的。之后,我将数组中的每个元素都替换为新的 .getAttribute("src")
.
var imageSource = await page.evaluate(() => {
imgQuery = document.querySelectorAll("img");
imgQuerySources = [...imgQuery].map((e) => e.getAttribute("src"));
return imgQuerySources;
});
console.log(imageSource)