JS 图像抓取工具

JS Image scraper

我认为制作一个基本的图像抓取工具会是一个有趣的项目。下面的代码可在网站的控制台中运行,但我不知道如何通过我的 app.js.

使其运行

var anchors = document.getElementsByTagName('a');
var hrefs = [];
for(var i=0; i < anchors.length; i++){ 
var src = anchors[i].href;
  if(src.endsWith(".jpeg")) {
    hrefs.push(anchors[i].href);
}} console.log(hrefs);

我认为使用 puppeteer 是个好主意,但我的知识太有限,无法确定这是否正确。这是我的木偶代码:

const puppeteer = require("puppeteer");

async function scrape(url) {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto(url);

    var anchors = await page.evaluate(() => document.getElementsByTagName('a'));   
    
    var hrefs = [];
    for(var i=0; i < anchors.length; i++){ var img = anchors[i].href;
      if(img.endsWith(".jpeg")) {
        hrefs.push(anchors[i].href);
    }} console.log({hrefs}, {img});
    
    browser.close();
}

我知道代码的最后一部分是错误的,但我找不到要写的内容的可靠答案。

感谢您抽出宝贵时间。

page.evaluate() can only transfer serializable values (roughly, the values JSON can handle). As document.getElementsByTagName() returns a collection of DOM elements that are not serializable (they contain methods and circular references), each element in the collection is replaced with an empty object. You need to return either serializable value (for example, an array of texts or href attributes) or use something like page.$$(selector) and ElementHandle API.

Web API 未在 .evaluate() 参数函数之外定义,因此您需要将所有 Web API 部分放在 .evaluate() 参数函数中,并且 return 来自它的可序列化数据。

const puppeteer = require("puppeteer");

async function scrape(url) {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto(url);

    const data = await page.evaluate(() => {
        const anchors = document.getElementsByTagName('a');
        const hrefs = [];
        for (let i = 0; i < anchors.length; i++) {
            const img = anchors[i].href;
            if (img.endsWith(".jpeg")) {
                hrefs.push(img);
            }
        }
        return hrefs;
    });
    console.log(data);

    await browser.close();
}