首页 > 解决方案 > 如何使用 Puppeteer 选择可变数量的 href 属性?

问题描述

我正在尝试href使用 Puppeteer 从画廊中选择一些可变数量的属性:

const GALLERY_SELECTOR = '#photosarea > ul > li:nth-child(1) > a';

let galleryImageHref = await page.evaluate((sel) => {
     return document.querySelector(sel).getAttribute('href');
}, GALLERY_SELECTOR);

console.log(  "image gallery link: " + galleryImageHref);

我上面的代码用于选择单个图像链接,但是我不知道如何遍历我试图抓取的画廊中可能存在的任何数量的图像,这可能是 0 个或更多。

我正在抓取的示例 HTML:

<div class="contentbox profilephotosarea" id="photosarea" style="width:613px;float:right;text-align:center;">
    <ul>
        <li><a href="/photo.php?picid=5026734&amp;u=galleryName" class="pr"><img src="/p/2020-04/galleryName/02487b00dfb51e7fe6aaa04dba9037da-thumb.jpg"></a><br></li>

        <li><a href="/photo.php?picid=5033539&amp;u=galleryName" class="pr"><img src="/p/2020-04/galleryName/f8eec9f0c2cd1db89968383cc9e6e0a5-thumb.jpg"></a><br></li>
    </ul>
</div>

我该怎么办?

谢谢。

标签: javascriptpuppeteer

解决方案


只需将其更改为:

return [...document.querySelectorAll(sel)].map(a => a.getAttribute('href'));

推荐阅读