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

Puppeteer截图前删除指定Div的实现问题及报错排查

解决Puppeteer删除元素时的Null错误问题

错误原因

报错Cannot read properties of null (reading 'remove')是因为你指定的部分选择器在页面上找不到匹配元素,document.querySelector()返回了null,此时调用remove()就会触发该错误。

修正后的删除元素代码

修改page.evaluate代码,先检查元素是否存在再执行删除操作;若需要删除同选择器下的所有元素,改用querySelectorAll确保全覆盖:

await page.evaluate(() => {
  const selectorsToRemove = ['.ce45', '.d20', '.cc27'];
  selectorsToRemove.forEach(selector => {
    const elements = document.querySelectorAll(selector);
    elements.forEach(el => el.remove());
  });
});

完整脚本整合

将删除代码放在等待目标元素加载完成之后、获取组件和截图之前:

await page.setViewport({
    width: 1368,
    height: 768
});

// 等待目标元素加载完成
await page.waitForSelector(`.${url.id.toLowerCase()}`).then(() => console.log('scraped', url.id.toLowerCase()));        

// 删除干扰元素
await page.evaluate(() => {
  const selectorsToRemove = ['.ce45', '.d20', '.cc27'];
  selectorsToRemove.forEach(selector => {
    const elements = document.querySelectorAll(selector);
    elements.forEach(el => el.remove());
  });
});

// 获取目标组件并截图
const component = await page.$(`.${url.id.toLowerCase()}`);     
const bounding_box = await component.boundingBox();  
await component.screenshot({
   path: `./${url.id.toLowerCase()}.png`,
   clip: {
      x: bounding_box.x,
      y: bounding_box.y,
      width: Math.min(bounding_box.width, page.viewport().width),
      height: Math.min(bounding_box.height, page.viewport().height),
   }
});

额外说明

  • querySelectorAll会返回所有匹配选择器的元素,避免遗漏同类型干扰项;
  • 即使选择器无匹配元素,querySelectorAll返回空集合,forEach不会执行操作,因此不会触发错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 14:54:09