cheerio with ionic creation of API

fdbelqdn  于 2023-05-05  发布在  Ionic
关注(0)|答案(1)|浏览(167)

我正在创建一个离子应用程序。我正在使用Cheerio和Node.js来抓取一个网站。我无法将整个数组返回到localhost,它只返回第一个对象。如何返回整个数组?
这是抓取代码(scraper.js)

const request = require('request')
const cheerio = require('cheerio');

request('https://mywebsite', (error, response, html) => {
    if (!error && response.statusCode == 200) {
        const $ = cheerio.load(html)
        const art = $('article').each((i, el) => {
            const title = $(el)
                .find('.entry-title.mh-posts-grid-title')
                .text();
            const link = $(el)
                .find('a')
                .attr('href');
            const image = $(el)
                .find('.mh-thumb-icon.mh-thumb-icon-small-mobile')
                .text()
            const Arra = { title: [title], link: [link], image: [image] }
            exports.Arra = Arra

这是我导出数据的代码(document.js)

const express = require("express");
const ok = require('./ok')
const app = express();
const porta = '8000'


app.get('/', (req, res) => {
    res.send(ok.Arra);
})

app.listen(porta, () => {
    console.log(`Server ex ${porta}`);
});
nmpmafwu

nmpmafwu1#

如果发布的代码是您的代码的总和,那么问题可能是缺少结束标记。应如下所示:

const request = require('request');
const cheerio = require('cheerio');

const Arra = [];

request('https://mywebsite', (error, response, html) => {
    // reset Array on each call
    Arra = [];
    if (!error && response.statusCode == 200) {
        const $ = cheerio.load(html)
        console.log('the array I am going to iterate over is', $);
        const art = $('article').each((i, el) => {
            const title = $(el)
                .find('.entry-title.mh-posts-grid-title')
                .text();
            const link = $(el)
                .find('a')
                .attr('href');
            const image = $(el)
                .find('.mh-thumb-icon.mh-thumb-icon-small-mobile')
                .text();
            // you must push each result into the array otherwise you are just going to have one result.
            Arra.push({ title: [title], link: [link], image: [image] });
    } // close of .each block
  }// close of if block
 }// close of request block
exports.Arra = Arra;

相关问题