javascript - 如何使用 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&u=galleryName" class="pr"><img src="/p/2020-04/galleryName/02487b00dfb51e7fe6aaa04dba9037da-thumb.jpg"></a><br></li>
<li><a href="/photo.php?picid=5033539&u=galleryName" class="pr"><img src="/p/2020-04/galleryName/f8eec9f0c2cd1db89968383cc9e6e0a5-thumb.jpg"></a><br></li>
</ul>
</div>
我该怎么办?
谢谢。
解决方案
只需将其更改为:
return [...document.querySelectorAll(sel)].map(a => a.getAttribute('href'));
推荐阅读
- c - 重新编码 malloc:代码签名被阻止 mmap()
- c++ - 将显式指定的函数模板重载作为模板参数传递的正确语法是什么?
- android - 图像旋转一定角度后计算新坐标
- python - 为什么我的 tensorflow 模型输出在 x 个时期后变为 NaN?
- python-3.x - python3.6.5 urllib.error.URLError:
- javascript - 如何在Javascript中检查它是否是夜间?
- hibernate - 带注释的类 + cfg.xml = org.hibernate.MappingException:未知实体
- r - rbindlist data.frames 的列表列并选择唯一值
- visual-studio-lightswitch - 按下键时如何终止循环的执行?
- linux - 迭代 Ansible 设置命令