繁体   English   中英

Web 在两个标签之间进行抓取,使用 cheerio

[英]Web scraping between two tags, using cheerio

各位晚上好,

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

<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)。 我开始写一个function,但是遇到了上面描述的问题。 如何让 function 明白我需要在数组的一个元素中的 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()

我至少看到了几种方法,具体取决于您想要什么。

也许你想要 select 一个<h3> ,比如第一个,然后遍历到它之后的<h3> ,收集所有元素并忽略所有其他<h3>标签:

const $ = cheerio.load(html);
const text = $("h3")
  .first()
  .nextUntil("h3")
  .map((i, e) => $(e).text())
  .toArray();
console.log(text);

这给出:

[
  ' Sub-Text A',
  ' some text ',
  ' Sub-Text B',
  ' some text ',
  ' Sub-Text C',
  ' some text '
]

如果您愿意,这些可以很容易地连接起来。

另一种解释是您希望将所有<h2>段分块到单独的子数组中:

const cheerio = require("cheerio"); // 1.0.0-rc.12

const html = `<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>
<h4> B STUFF</h4>
<div class="Sub-Class D"> B STUFF </div>

<h3>Text C</h3>
<div>C STUFF</div>
</div>
</form>
</body>`;

const $ = cheerio.load(html);
const groups = [...$("h3")]
  .map(e => [...$(e).nextUntil("h3")].map(e => $(e).text()));
console.log(groups);

这给

[
  [
    ' Sub-Text A',
    ' some text ',
    ' Sub-Text B',
    ' some text ',
    ' Sub-Text C',
    ' some text '
  ],
  [ ' B STUFF', ' B STUFF ' ],
  [ 'C STUFF' ]
]

也可以看看:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM