Good evening everyone,
I study cheerio and try to parse the data from the site. Its structure is below, I'll go straight to body:
<body>
<form>
<div class="a">
<h3>Text A</h3>
<h4> Sub-Text A</h4>
<div class="Sub-Class A"> some text </div>
<h4> Sub-Text B</h4>
<div class="Sub-Class B"> some text </div>
<h4> Sub-Text C</h4>
<div class="Sub-Class C"> some text </div>
<h3>Text B</h3>
...
...
<h3>Text C</h3>
</div>
</form>
</body>
The task is to parse the data into the array from h3 to the next h3 (i.e., h3, all h4 and div following it, but to the next h3). I started writing a function, but I ran into the problem described above. How to let the function understand that I need to write everything down after h3 in one element of array, but before the next h3?
The code that I have at the moment:
const Nightmare = require('nightmare');
const cheerio = require('cheerio');
const nightmare = Nightmare({show: true})
nightmare
.goto(url)
.wait('body')
.evaluate(()=> document.querySelector('body').innerHTML)
.end()
.then(response =>{
console.log(getData(response));
}).catch(err=>{
console.log(err);
});
let getData = html => {
data = [];
const $ = cheerio.load(html);
$('form div.a').each((i, elem)=>{
data.push({
});
});
return data;
}
You can just follow the "next()" element until you find a h3:
let texts = $('h3').map((i, el) => {
let text = ""
el = $(el)
while(el = el.next()){
if(el.length === 0 || el.prop('tagName') === 'H3') break
text += el.text() + "\n"
}
return text
}).get()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With