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

如何用NodeJS单次获取指定网站的首个h4元素?原代码返回全部文本

Solution: Grab Only the First <h4> Element with Node.js & Cheerio

Got it, the issue with your current code is that $('h4') selects all <h4> elements on the page, which is why you're getting all their text combined. Let's tweak this to target just the first one.

How to Fix It

Cheerio gives you a couple straightforward ways to grab the first matching element:

  1. Use the .first() method (clean and readable):
    Change title = $('h4') to title = $('h4').first()

  2. Use the :first pseudo-selector:
    Alternatively, you can write the selector directly as $('h4:first')

Both approaches will target only the first <h4> element in the parsed HTML.

Modified Full Code

Here's your updated code with the fix applied (using .first() for clarity):

// Make sure isCheckedToday is declared outside the interval to persist its state
let isCheckedToday = false;

setInterval(() => {
  var d = new Date();
  if (d.getHours() === 21) {
    request({
      method: 'GET',
      url: 'http://scripts.ivao-de.net/api/?type=training'
    }, (err, res, body) => {
      if (err) return console.error(err);
      let $ = cheerio.load(body);
      let title;
      if(isCheckedToday === false) {
        // Target only the first h4 element
        title = $('h4').first();
        isCheckedToday = true;
        console.log(title.text());
      }
    });
  } else {
    isCheckedToday = false;
  }
}, 3000);

Quick Notes

  • I added a declaration for isCheckedToday at the top since it needs to persist across interval runs (your original code might have this elsewhere, but it's good to make explicit).
  • The .first() method filters the cheerio collection down to just the first matching element, so title.text() will now only return the text of that single <h4>.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 11:54:10