最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - .find is not a function on cheerio object - Stack Overflow

programmeradmin11浏览0评论
  let playersCell = `
    <td class="foo" colspan="2">
      <a href="example">
        <span class="bold">John Beluga</span>
         - Sarah Jay.
       </a>
    </td>
    `

let players = cheerio.load(playersCell)
players.find('a').html()

I try to load a html string into cheerio.js and find an a tag, but I am getting

[TypeError: players.find is not a function]

Console.log shows for players

  let playersCell = `
    <td class="foo" colspan="2">
      <a href="example.">
        <span class="bold">John Beluga</span>
         - Sarah Jay.
       </a>
    </td>
    `

let players = cheerio.load(playersCell)
players.find('a').html()

I try to load a html string into cheerio.js and find an a tag, but I am getting

[TypeError: players.find is not a function]

Console.log shows for players

Share Improve this question asked Jun 29, 2017 at 18:06 user3568719user3568719 1,05615 silver badges35 bronze badges 1
  • Can you try this let players = cheerio.load(playersCell); players('.foo').find('a').html() – Hassan Imam Commented Jun 29, 2017 at 18:15
Add a ment  | 

2 Answers 2

Reset to default 6

I got .find is not a function, and when I looked at the object in the console that I was trying to find, it said its type was tag. I realized I needed to wrap the object again.

let results = $('.your .query')
results.each((i, r) => {
  $(r).find('.your .next .query')
})

find is a method that appears on DOM search results. You need to create a result before you can use find.

For example:

let playersCell = `<table><tr>
    <td class="foo" colspan="2">
      <a href="example.">
        <span class="bold">John Beluga</span>
         - Sarah Jay.
       </a>
    </td></tr></table>
    `

let players = cheerio.load(playersCell);
console.log(players('td').find('a').html());
<script src="https://wzrd.in/standalone/cheerio@latest"></script>

But in this case, there is no need to. You can just use the initial search directly:

let playersCell = `
    <td class="foo" colspan="2">
      <a href="example.">
        <span class="bold">John Beluga</span>
         - Sarah Jay.
       </a>
    </td>
    `

let players = cheerio.load(playersCell);
console.log(players('a').html());
<script src="https://wzrd.in/standalone/cheerio@latest"></script>

发布评论

评论列表(0)

  1. 暂无评论