如何用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:
Use the
.first()method (clean and readable):
Changetitle = $('h4')totitle = $('h4').first()Use the
:firstpseudo-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
isCheckedTodayat 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, sotitle.text()will now only return the text of that single<h4>.
内容的提问来源于stack exchange,提问作者btwlouis
相关产品推荐
相关产品推荐

