从舞台建设中获取数据 (Cheerio)

Getting data from strage construction (Cheerio)

<div class="testClass">
<strong>Num1</strong> 
: 16X
<br>
<strong>Num2</strong> 
: 16X
<br>
<strong>Num3</strong>
 : 12X
<br>
<strong>Num4</strong>
 : 12X
<br>

我需要得到 "Num1" 等,以及 ":16x" 等。 但是怎么才能得到“:16x”我不知道,它不是标签之间,什么的。

我正在使用 node.js 和 cheerio 进行此操作。这是一个网络抓取工具。

在 Cheerio 中找不到任何可以开箱即用的东西,所以我破解了这个:

const cheerio = require('cheerio');

const html = `<div class="testClass">
<strong>Num1</strong>
: 16X
<br>
<strong>Num2</strong>
: 16X
<br>
<strong>Num3</strong>
 : 12X
<br>
<strong>Num4</strong>
 : 12X
<br>
</div>`;


const $ = cheerio.load(html);

let num, val;
const results = [];

$('.testClass').contents().map((i, el) => {
    // console.log(i, i % 4, $(el).text().trim());

    if (i % 4 === 1)
        num = $(el).text().trim();
    if (i % 4 === 2)
        val = $(el).text().trim().match(/: ([a-zA-Z0-9]+)/)[1];
    if (i % 4 === 3)
        results.push({ [num]: val });
});

console.log(results);

$('.testClass').contents()(来自注释掉的 console.log)的结果是:

0 0 ''
1 1 'Num1'
2 2 ': 16X'
3 3 ''
4 0 ''
5 1 'Num2'
6 2 ': 16X'
7 3 ''
8 0 ''
9 1 'Num3'
10 2 ': 12X'
11 3 ''
12 0 ''
13 1 'Num4'
14 2 ': 12X'
15 3 ''
16 0 ''

使用 remainder operator 和一些正则表达式,我们能够提取您想要的值:

[
    { Num1: '16X' },
    { Num2: '16X' },
    { Num3: '12X' },
    { Num4: '12X' }
]