首页 > 解决方案 > 单击包含特定 alt 标签的元素

问题描述

我目前有以下代码:

<div class="c-form-field c-form-field--radio SelectStyle col">
<label for="input_radio_style_17" aria-hidden="false" class="">
<span class="c-form-label-content">
<span class="c-image product c-image--square">
<span class="LazyLoad is-visible">
<img src="https://images.example.com/23434234.jpg" alt="Green picture frame" id="I0065001">
</span>
</span>
</span>
</label>
<input name="style" aria-labelledby="styleI0065001" id="input_radio_style_17" type="radio" required="" value="17"></div>

我在页面上有大约 20 个,有时这个数字会发生变化,我需要做的是遍历每个并找到包含特定 alt 标签的那个,然后单击它。在上面的示例中,我需要遍历一堆并找到包含的那个alt="Green picture frame",然后单击它。

首先,我会像这样使用 SelectStyle 遍历每个元素。

const imgs = await page.$$eval('.SelectStyle', imgs => imgs.map{
    return (img => img.getAttribute('alt'))
});

从这里我有点卡住了,我将如何返回匹配的元素然后单击它?

标签: javascriptnode.jspuppeteer

解决方案


您可以使用CSS 属性选择器解决此问题

const imgs = await page.$$('.SelectStyle img[alt="Green picture frame"]');

推荐阅读