I'm trying to get a specific elements value with Cheerio however I'm unsure how. I've looked over the documentation and so far, no dice.
Website example of the value I'm trying to get, specifically the <dd>
that holds the number value of player count.
const URL = 'https://www.battlemetrics.com/servers/dayz/16108490';
axios(URL)
.then(response => {
const html = response.data
const $ = cheerio.load(html)
const players = []
$('.server-info', html).each(function() {
const scrape_test = $(this).text()
const pNum = $(this).find('dd').val()
players.push({
scrape_test,
pNum
})
})
console.log(players)
}).catch(err => console.log(err))
scrape_test is just ensuring that I'm actually receiving data and it does indeed grab the data including the value I need however I don't know how to refine it to grab specifically what I need.
The response from pNum is undefined, I've tried removing .val() in which I then receive 6 array elements however when I try to iterate over them to push them out, I then get another undefined. If I pick a specific position I equally get an undefined.
For the player count value, you can filter <dt>
elements by their text contents, then pull the next element to find the corresponding <dd>
:
const $ = cheerio.load(html);
const dt = [...$("dt")]
.find(e => $(e).text().trim().toLowerCase() === "player count");
console.log($(dt).next().text()); // => 7/65
Another option is the :contains()
pseudoselector and the adjacent sibling combinator:
const text = $('dt:contains("Player count") + dd').text();
See also Cheerio: How to select element by text content?
cheerio 1.0.0-rc.12