Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web scraping between two tags, using cheerio

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;
}
like image 371
Rickflar Avatar asked Mar 04 '26 12:03

Rickflar


1 Answers

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()
like image 124
pguardiario Avatar answered Mar 07 '26 02:03

pguardiario



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!