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

使用Cheerio提取表格第二列文本时遇.text()不是函数错误

Fixing the .text() is not a function Error in Your Cheerio Web Scraper

Hey there! Let's get that web scraping project back on track. The error you're hitting comes down to a small but important quirk in how Cheerio handles DOM elements when you use toArray(). Here's the breakdown and easy fixes:

Why the Error Happens

When you call .toArray() on a Cheerio selection, it converts Cheerio-wrapped elements into native DOM elements (the same type you’d work with in vanilla JavaScript). These native elements don’t have Cheerio’s .text() method—you need to wrap them back in a Cheerio object to use those convenient methods.

Solution 1: Skip toArray() and Use Cheerio’s .each()

This is the most straightforward approach. Instead of converting to an array, iterate directly over the Cheerio selection:

const rq = require('request'); 
const cheerio = require('cheerio'); 

rq(url, (err, res, html) => { 
  // Add basic error handling for failed requests
  if (err || res.statusCode !== 200) {
    console.error('Request issue:', err || `Status code: ${res.statusCode}`);
    return;
  }

  let $ = cheerio.load(html); 
  // Iterate over each matching td element
  $('#table-id > tbody > tr > td.data').each((_, item) => { 
    // Wrap the native element in $() to use Cheerio's .text()
    const cellText = $(item).text().trim();
    console.log(cellText);
    // You can now process cellText for your value integration
  }); 
});

Solution 2: Keep toArray() but Wrap Elements in Cheerio

If you prefer working with arrays (for mapping or other array methods), just wrap each native element back in a Cheerio object before calling .text():

const rq = require('request'); 
const cheerio = require('cheerio'); 

rq(url, (err, res, html) => { 
  if (err || res.statusCode !== 200) {
    console.error('Request issue:', err || `Status code: ${res.statusCode}`);
    return;
  }

  let $ = cheerio.load(html); 
  const cellTexts = $('#table-id > tbody > tr > td.data').toArray().map(item => { 
    // Wrap item in $() to access Cheerio methods
    return $(item).text().trim();
  }); 

  console.log(cellTexts);
  // Now you have an array of clean text values to integrate
});

Bonus Tip

I added .trim() to both examples—this removes extra whitespace, newlines, and tabs from the extracted text, which will make it much easier to parse and integrate those numerical values you need.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:58:57