如何通过解析 HTML 平台 Node.js 使用 jQuery 准确获取字段包含的内容

How to get exactly what field contains using jQuery by parsing HTML platform Node.js

我正在尝试解析 HTML 标记 <blockquote> 并希望获得 id 属性。

并且在控制台中我得到一个空字符串,我应该怎么做才能修复它?提前致谢。

在这种情况下我需要这个输出:m178043663

HTML:

<blockquote id="" class="post-message">                                              
      УНИЖЕНИЯ ТРЕД<strong> WEBM&#47;MP4</strong>
</blockquote>

我试图解析这个:

request('https://2ch.hk/b/',(error,response,body)=>{
  const $ = cheerio.load(body)
  const threadfind = $('blockquote').text()

  if(threadfind && threadfind.includes('WEBM'))
  { // thread find blockquote 

     const threadid= threadfind.includes("WEBM")
      var rtrrr = threadfind.attr('id')
     console.log(rtrrr)
  }
})

如图所示

<blockquote id="" class="post-message">                                              
      УНИЖЕНИЯ ТРЕД<strong> WEBM&#47;MP4</strong>
</blockquote>

<blockquote> 元素中没有 id 所以它 return 空字符串。

此外,此处的代码 const threadfind = $('blockquote').text() 使您的 threadfind 成为字符串变量,因此您无法从 threadfind.attr('id')

行中获取 id

这里 demo 用于获取元素 ID。

这里是解决方案

 request('https://2ch.hk/b/',(error,response,body)=>{
      const $ = cheerio.load(body)
      const threadfind = $('blockquote')

      if(threadfind && threadfind.text().includes('WEBM'))
      { // thread find blockquote 
         const threadid= threadfind.attr('id')
         console.log(threadid)
      }
    })