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

如何使用Flutter/Dart爬取网页中img标签的src属性值

爬取img标签src属性问题解决方案

问题原因

你当前代码返回非预期结果的核心原因是:attributes['src'] 获取到的是DOM属性实例对象,而非直接的src字符串值,需要读取该对象的value属性才能拿到实际的链接内容。

修正后的基础代码

final picp = document.getElementsByClassName("inline-table");
pics = picp.map((e) => e.getElementsByTagName("img")[0].attributes['src']?.value ?? '').toList();

可选优化方案

如果存在部分inline-table节点下没有img标签、或是img标签无src属性的场景,可以增加判空和过滤逻辑,避免运行报错同时剔除无效结果:

final picp = document.getElementsByClassName("inline-table");
pics = picp.map((e) {
  final imgNodes = e.getElementsByTagName("img");
  if (imgNodes.isEmpty) return '';
  return imgNodes[0].attributes['src']?.value ?? '';
}).where((srcStr) => srcStr.isNotEmpty).toList();

如果按上述方案修改后仍无法获取到正确值,可以检查目标页面的img标签是否使用了懒加载方案,真实图片链接可能存放在data-src、data-original这类自定义属性中,对应调整代码中取值的属性名即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 05:15:04