首页 > 解决方案 > Node.js Cheerio 返回空且没有错误

问题描述

我正在尝试从具有如下结构的表中获取数据:

<table id="ros_table" class="info" style="display: none;">
    <tr>
        <th>First</th>
        <th>Second</th>
        <th>Third</th>
        <th>Forth</th>
        <th>Fifth</th>
        <th>Six</th>
    </tr>
    <tr>
        <td style="white-space: nowrap;"><a href="#">120241</a></td>
        <td style="white-space: nowrap;"><a href="#">69801:001:0255</a></td>
        <td>Name</td>
        <td>Name 2</td>
        <td><span style="white-space: nowrap;">90400 m<sup>2</sup></span> <span style="white-space: nowrap;">(9.04 ha)</span></td>
        <td style="white-space: nowrap;">jah</td>
    </tr>

我使用的代码是这样的:

fetchData(url).then( (res) => {
    const html = res.data;
    const $ = cheerio.load(html);
    const statsTable = $('.table#ros_table > tr');
    statsTable.each(function() {
        let title = $(this).find('td').text();
        console.log(title);
    });
})

async function fetchData(url){
    console.log("Looking for stuff you need...")
    // Make the call
    let response = await axios(url).catch((err) => console.log(err));

    if(response.status !== 200){
        console.log("Blah, this did not work out");
        return;
    }
    return response;
}

只需一个简单的 que,它就可以正常工作,但由于某种原因,我可以让它在这张桌子上工作。

标签: node.jsweb-scrapingcheerio

解决方案


你需要return从每个.then()块中取出一些东西,我假设你想要这样的东西?:

fetchData(url).then( (res) => {
    const html = res.data;
    const $ = cheerio.load(html);
    const statsTable = $('.table#ros_table > tr');
    return statsTable.map(function() {
        return $(this).find('td').text();
    });
})

推荐阅读