【问题标题】:Click on element that contains a specific alt tag单击包含特定 alt 标签的元素
【发布时间】:2020-06-17 03:07:09
【问题描述】:

我目前有以下代码:

<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'))
});

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

【问题讨论】:

    标签: javascript node.js puppeteer


    【解决方案1】:

    你可以通过CSS attribute selector解决这个问题

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

    【讨论】:

    • 我收到了这个错误:(node:55234) UnhandledPromiseRejectionWarning: E​​rror: Expected to get |string|或 |功能|作为第一个参数,但得到“未定义”。知道为什么吗? @hardkoded
    • 很抱歉@FabricioG 它应该是$$ 而不是`$$eval`
    猜你喜欢
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 2017-09-18
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多