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

使用Cheerio与Axios爬取DCInside青少年政策页面失败求助

解决Axios+Cheerio爬取DCInside青少年政策页面无法获取目标元素的问题

可能的原因及对应解决方法

  • 页面动态渲染导致初始HTML无目标内容
    部分网站会通过JavaScript渲染页面内容,Axios仅能获取服务器返回的初始HTML。先检查返回的原始代码是否包含目标元素:

    axios.get('http://nstatic.dcinside.com/company/rules/youth_policy.html')
      .then(res => {
        console.log(res.data); // 打印完整HTML,搜索#bodyWrap2是否存在
      })
    

    如果初始HTML里找不到目标元素,需改用Puppeteer这类支持JS渲染的工具爬取。

  • 请求头模拟不完整,服务器返回差异化内容
    部分网站会根据请求头判断访问来源,返回不同内容。尝试添加更贴近真实浏览器的请求头:

    const headers = {
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36',
      'Accept-Language': 'ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7',
      'Referer': 'http://nstatic.dcinside.com/company/rules/'
    };
    
    axios.get('http://nstatic.dcinside.com/company/rules/youth_policy.html', { headers })
      .then(res => {
        const $ = cheerio.load(res.data);
        const targetText = $('#bodyWrap2 .cnt03 dl:nth-child(1)').text().trim();
        console.log(targetText);
      })
    
  • 选择器定位逻辑需分步排查
    不要直接使用嵌套过深的选择器,分步验证每个节点是否存在,定位问题环节:

    const $ = cheerio.load(res.data);
    const bodyWrap = $('#bodyWrap2');
    console.log('bodyWrap存在数量:', bodyWrap.length);
    if (bodyWrap.length > 0) {
      const cnt03 = bodyWrap.find('.cnt03');
      console.log('cnt03存在数量:', cnt03.length);
      if (cnt03.length > 0) {
        const targetDl = cnt03.find('dl').first();
        console.log('目标文本:', targetDl.text().trim());
      }
    }
    
  • 响应编码解析错误
    若网站返回非UTF-8编码内容,Axios可能解析异常。可指定响应编码:

    axios.get('http://nstatic.dcinside.com/company/rules/youth_policy.html', {
      responseEncoding: 'utf-8'
    })
    

    若仍无效,可借助iconv-lite库手动转换编码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 17:53:14