从strage建设中获取数据(Cheerio)

时间:2017-05-16 11:57:06

标签: node.js web-scraping cheerio

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

我需要得到&#34; Num1&#34;等,以及&#34;:16x&#34;等。 但我怎样才能得到&#34;:16x&#34;我不知道,它不是什么东西。或者什么。

我使用带有cheerio的node.js来做这件事。它是一个网络刮刀。

1 个答案:

答案 0 :(得分:0)

在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' }
]