使用 cheerio 在两个标签之间进行网页抓取

Web scraping between two tags, using cheerio

大家晚上好,

我研究了 cheerio 并尝试解析来自站点的数据。它的结构如下,我直接上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>

任务是将数据解析到数组中,从h3到下一个h3(即h3,所有h4和它后面的div,但到下一个h3)。我开始写一个函数,但是我运行陷入了上面描述的问题。如何让函数理解我需要在数组的一个元素中的 h3 之后,但在下一个 h3 之前写下所有内容?

我目前手上的代码:

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;
}

您可以跟随 "next()" 元素直到找到 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()