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

Puppeteer无法检测选择器求助:抓取元素时报TypeError错误

Puppeteer抓取Vivino页面元素报错的解决办法

你遇到的Cannot read properties of null (reading 'textContent')错误,核心原因是Puppeteer执行时目标元素未完成加载,或选择器过于脆弱导致匹配失败,以下是具体修复方案:

1. 等待元素完全渲染后再获取

domcontentloaded仅等待DOM结构加载完成,但Vivino页面部分内容是动态渲染的(比如通过AJAX或前端框架加载),此时直接查询元素会返回null。改用waitForSelector等待元素出现后再读取内容:

// 等待目标元素加载,超时时间设为10秒(可按需调整)
const alcoholElement = await winePage.waitForSelector(
  "div.wrap div#wine-page-lower-section div.vintagePage__bottom--1fcqg div.inner div:nth-child(5) table tbody tr:nth-child(5) td span",
  { timeout: 10000 }
);
const alcohol = await alcoholElement.evaluate(el => el.textContent);
console.log(alcohol);

2. 使用更稳定的选择器

你当前的选择器依赖过多层级和nth-child定位,一旦页面结构微调就会失效。建议通过内容匹配定位元素,比如找到标注"Alcohol"的行再提取对应值:

const alcohol = await winePage.evaluate(() => {
  // 遍历所有表格行
  const rows = document.querySelectorAll("table tbody tr");
  for (const row of rows) {
    const labelCell = row.querySelector("td:first-child");
    if (labelCell?.textContent.trim() === "Alcohol") {
      return row.querySelector("td span").textContent.trim();
    }
  }
  return null; // 未找到时返回null
});
console.log(alcohol);

3. 规避反爬机制

Vivino可能会识别爬虫并返回异常页面,可通过以下方式模拟真实浏览器:

  • 设置User-Agent:
    await winePage.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36");
    
  • 添加合理等待:
    await winePage.waitForTimeout(2000); // 等待2秒,根据页面加载速度调整
    

4. 验证目标页面正确性

检查wine.link是否与你手动测试的URL完全一致,避免因链接参数错误导致页面结构不同。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 21:23:28