簡體   English   中英

Node.js - 無法使用 Cheerio 存儲預期數據

[英]Node.js - Impossible to store the expected data with Cheerio

我正在嘗試抓取一個網站,但我的輸出有一個大問題。

我希望恢復站點上的名稱,它會找到我的數據,但是當我嘗試存儲此值時,我只能存儲值“null”。

我是編程的初學者,我沒有研究過承諾、回調和異步,但我認為這與問題密切相關。

這是我使用.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”數據存儲在一個變量中以對其進行操作時,我不能,因為它返回“undefined”或“null”。

你能幫我么 ? 謝謝。

我建議使用基於承諾的方法,恕我直言,這提供了最易讀的代碼。

您可以從檢索函數返回一個承諾。

我還建議使用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!");

有 2 個元素的類p.fs-12 a.Link 所以如果你想選擇第二個,你應該使用另一種cheerio方法。

.text()也用於從 html 元素中檢索文本值。 如果您想獲取 html 元素本身,則不應使用它。

您需要的查詢是:

$('div#presentationlien.FichePresentation__link.mt-13 p.fs-12 a.Link').eq(2).parent();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM