You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Node.js+jsdom获取<a>标签内img元素的关联详情?

获取锚点标签内图片与跳转地址的关联信息

使用Node.js结合jsdom时,能分别通过querySelectorAll("img")和querySelectorAll("a")枚举图片和锚点标签,但需要建立二者的关联——即获取点击图片时对应的跳转地址,同时拿到图片的src和alt信息。

示例HTML

<a href="http://www.yahoo.com">
  <img src="https://s.yimg.com/nq/nr/img/yahoo_mail_global_english_white_1x.png" alt="Yahoo Mail Image">
</a>

改进后的Node.js代码

var links = dom.window.document.querySelectorAll("a");
links.forEach(function(link) {
    // 获取当前锚点内的图片元素
    var img = link.querySelector("img");
    if (img) {
        console.log('跳转地址: ' + link.href);
        console.log('图片地址: ' + img.src);
        console.log('图片描述: ' + img.alt);
        console.log('---');
    }
});

输出结果

跳转地址: http://www.yahoo.com/
图片地址: https://s.yimg.com/nq/nr/img/yahoo_mail_global_english_white_1x.png
图片描述: Yahoo Mail Image
---

内容的提问来源于stack exchange,提问作者William Vincent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 18:39:55