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

如何使用Puppeteer获取维基百科页面的图片src?

解决Puppeteer获取维基百科芒果品种图片src报错问题

问题根源

  1. 部分表格行没有对应的图片元素,直接访问row.querySelector('a > img').src时,querySelector返回null,进而触发Cannot read properties of null (reading 'src')错误。
  2. 代码中row.querySelectorAll('a > img').getAttribute('src')写法错误:querySelectorAll返回的是节点列表(NodeList),不能直接调用getAttribute方法,需针对单个元素操作。

修正后的代码

const recordList = await page.$$eval(
  'div#mw-content-text > div.mw-parser-output > table > tbody > tr',
  (trows) => {
    let rowList = []
    trows.forEach((row) => {
      let record = { name: '', image: '', origin: '', notes: '' }

      // 先获取图片元素,存在再取src,避免空值报错
      const imgElement = row.querySelector('td:first-child a > img')
      record.image = imgElement ? imgElement.src : ''

      const tdList = Array.from(row.querySelectorAll('td'), (column) => column.innerText) 

      record.name = tdList[0] || ''
      record.origin = tdList[2] || ''
      record.notes = tdList[3] || ''
      rowList.push(record)
    })

    return rowList
  }
)

关键调整说明

  • 增加元素存在性判断:imgElement ? imgElement.src : '',确保没有图片的行不会触发报错,而是赋值为空字符串。
  • 优化图片选择器为td:first-child a > img,精准定位到每行第一个单元格内的图片,避免误选页面其他位置的图片。
  • 移除无效的querySelectorAll调用,同时给tdList的取值加上|| ''兜底,防止部分行单元格数量不足时出现undefined。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 20:31:10