【问题标题】:Web scraping between two tags, using cheerio使用cheerio在两个标签之间进行网页抓取
【发布时间】:2023-03-24 00:19:01
【问题描述】:

大家晚上好,

我研究 Cheerio 并尝试解析来自该站点的数据。它的结构如下,我直接上正文:

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

【问题讨论】:

  • 当前结果与您想要的结果有何不同?
  • 你在说什么?我还没有。结果,我想要一个包含元素的数组,由 h3、所有 h4 和 div 组成。类似:Array= [ {h3, h4, div, h4, div}, ... {h3, h4, div, h4, div]

标签: javascript reactjs web-scraping cheerio


【解决方案1】:

你可以跟着“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()

【讨论】:

  • 非常感谢!这就是我一直在寻找的。​​span>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-03
  • 2020-07-16
  • 1970-01-01
相关资源
最近更新 更多