javascript - Node.js - 无法使用 Cheerio 存储预期数据

标签 javascript node.js asynchronous web-scraping cheerio

我正在尝试抓取一个网站,但输出有一个大问题。

我希望恢复网站上的名称,它找到了我的数据,但是当我尝试存储该值时,我只能存储值“null”。

我是编程初学者,我没有研究过 Promise、回调和异步,但我认为这与问题密切相关。

这是我使用 .text() 时的 Node.js 代码

const http = require('follow-redirects/http');
const https = require('follow-redirects/https');
const cheerio = require('cheerio');

https.get('https://www.example.com/search?q=' + entreprise, response => {
  response.on('data', chunk => {
    const $ = cheerio.load(chunk, {
      xmlMode : false
    });

    domaine = $('div#presentationlien.FichePresentation__link.mt-13 p.fs-12 a.Link').text()

    JSON.parse(JSON.stringify(domaine))

    console.log(domaine);

  });

}).on('error', err => {
  console.error(err);
});

HTML:

    ...
    <div id="synthese" class="break-word mt-29">
        <p class="fs-12">
            <a class="lien" href="/societe/renault-sas-780129987.html">RENAULT SAS</a>, soci&#xFFFD;t&#xFFFD; par actions simplifi&#xFFFD;e est active depuis 48 ans.<br>Localis&#xFFFD;e &#xFFFD; BOULOGNE-BILLANCOURT (92100), elle est sp&#xE9;cialis&#xE9;e dans le secteur d&apos;activit&#xFFFD; de la construction de v&#xFFFD;hicules automobiles. Son effectif comprends plus de 10 000 salari&#xE9;s.
        </p>


        <div id="presentationlien" class="FichePresentation__link mt-13"> 
            <p class="fs-12">Sur l&apos;ann&#xE9;e 2018 elle r&#xE9;alise un chiffre d&apos;affaires de <span class="synthesenumber">48333000000,00  EU</span>.</p>
            <p class="fs-12">Le total du bilan a augment&#xE9; de 0,97 % entre 2017 et 2018.</p>

            
            <p class="fs-12">Societe.com recense <a class="Link" href="#etab"><span id="synthnbetab" class="synthesenumber">219</span> &#xE9;tablissements <span id="synthnbetabexact"></span></a> et 4 <a class="Link" href="#event">&#xE9;v&#xE9;nements</a> notables depuis un an.</p>
            

            
            <p class="fs-12">
            <a class="Link" href="https://dirigeant.societe.com/dirigeant/Jean-Dominique.SENARD.69230073.html">Jean-Dominique SENARD</a>, est pr&#xFFFD;sident de la soci&#xFFFD;t&#xFFFD; RENAULT SAS.
            </p>
            

            
        </div>

            
            
    </div>
...

我想要获取的数据:

让-多米尼克·塞纳德

<p class="fs-12">
            <a class="Link" href="https://dirigeant.societe.com/dirigeant/Jean-Dominique.SENARD.69230073.html">Jean-Dominique SENARD</a>, est pr&#xFFFD;sident de la soci&#xFFFD;t&#xFFFD; RENAULT SAS.
            </p>

输出控制台:

219 établissements événementsJean-Dominique SENARD

但是当我尝试将“Jean-Dominique SENARD”数据存储在变量中以对其进行操作时,我不能,因为它返回“未定义”或“null”。

你能帮我一下吗?谢谢。

最佳答案

我建议使用基于 promise 的方法,恕我直言,这提供了最具可读性的代码。

您可以从检索函数返回一个 promise 。

我还建议使用 async/await语法,这进一步提高了可读性。

获得结果后,您可以在 testGetRequiredData() 中进一步操作它..

您也可以尝试替换该行:

domaine = $('div#presentationlien.FichePresentation__link.mt-13 p.fs-12 a.Link').text();

domaine = $('div#presentationlien.FichePresentation__link.mt-13 p.fs-12 a.Link').last().text();

这只会给出名称(但这可能不那么强大!)

例如:

const cheerio = require('cheerio');
const http = require('follow-redirects/http');
const https = require('follow-redirects/https');

function getRequiredData(url) {
    return new Promise((resolve, reject) => {
        https.get(url, response => {
            response.on('data', chunk => {
                const $ = cheerio.load(chunk, { xmlMode : false });
                domaine = $('div#presentationlien.FichePresentation__link.mt-13 p.fs-12 a.Link').text()
                resolve(domaine);
            });
        }).on('error', err => {
            reject(err);
        });
    });
}

async function testGetRequiredData(entreprise) {
    try { 
        const url = `https://www.example.com/search?q=${entreprise}`;
        let result = await getRequiredData(url);
        // Do whatever you wish with the result..
        console.log("Result:", result);
    } catch (error) {
        console.error(`testGetRequiredData: An error occurred:`, error);
    }
}

// Replace the parameter here..
testGetRequiredData("put entreprise here!");

关于javascript - Node.js - 无法使用 Cheerio 存储预期数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59857452/

相关文章:

mysql - Knex.js 在服务器端代码中验证查询结果

multithreading - Delphi 2007 中的 AsyncCall

javascript - jQuery val 函数不适用于隐藏字段?

javascript - 是否可以使用正则表达式 chop 字符串的开头?

javascript - 匹配所有值,替换为 OR 运算符

node.js - 如何使用 xero-node 库更新多个联系人

服务器上的 Node.js 和 Backbone.js 路由器

asp.net - 在asp.net中实时显示命令行程序的输出

angular - FakeAsync/tick (Async/whenStable) 与 detectChanges()

javascript - node.js/Swift/Stripe/Webtask 创建费用时出错