在 puppeteer 中获取具有特定类的 Image src

Hat*_*sam 4 javascript node.js web-scraping puppeteer

我有以下代码,我将所有 src 存储在一个数组中,我只想存储类名为 xyz 的 img

const imgs = await page.$$eval('img[src]', imgs => imgs.map(img => img.getAttribute('src')));
Run Code Online (Sandbox Code Playgroud)

我试图用户过滤,但我无法达到正确的语法来做到这一点。

Cer*_*nce 13

只需添加.xyz到您的查询字符串:

const imgs = await page.$$eval('img.xyz[src]', imgs => imgs.map(img => img.getAttribute('src')));
Run Code Online (Sandbox Code Playgroud)


Ben*_*ith 5

如果您想获取类 latest-photos 中的所有 SRC 地址:

<div class="latest-photos">

    <img src="/LogoImage.ashx?sn=14376&imgNbr=0" id="ctl00_ctl00_ctl00_cphMain_cphMiddle_cphCenterColumn_uctDiveInfoDisplay_img1" alt="OptionalI Image 1" width="170" style="vertical-align: top;" />
    <img src="/LogoImage.ashx?sn=14376&imgNbr=1" id="ctl00_ctl00_ctl00_cphMain_cphMiddle_cphCenterColumn_uctDiveInfoDisplay_img2" alt="OptionalI Image 2" width="170" style="vertical-align: top;" />
    <img src="/LogoImage.ashx?sn=14376&imgNbr=2" id="ctl00_ctl00_ctl00_cphMain_cphMiddle_cphCenterColumn_uctDiveInfoDisplay_img3" alt="Option
    
    alI Image 3" width="170" style="vertical-align: top;" />
</div>
Run Code Online (Sandbox Code Playgroud)

你用:

const imgs = await page.$$eval('.latest-photos img[src]', imgs => imgs.map(img => img.getAttribute('src')));
Run Code Online (Sandbox Code Playgroud)