【问题标题】:cheerio with ionic creation of APICheerio 使用离子创建 API
【发布时间】:2021-06-17 16:01:30
【问题描述】:

我正在创建一个离子应用程序。我正在使用 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}`);
});

【问题讨论】:

  • 查看数据样本也会有所帮助。您至少还缺少 scraper.js 代码中的几个结束标记。
  • 只返回第一个数组
  • 缺少哪些标签?
  • 1) 如果您使用 console.log('$ equals', $) 控制台中显示的内容。那是样本数据。 2) 在提供的示例中,您缺少请求行 { 、if 行 { 和 const art 行 { 的结束标记
  • 你能解释一下吗

标签: javascript node.js arrays ionic-framework cheerio


【解决方案1】:

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

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;

【讨论】:

  • 她很有帮助
  • @paul 很高兴为您提供帮助,请点击复选框并接受为正确:)
猜你喜欢
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-05
  • 1970-01-01
  • 2020-09-03
  • 2019-09-17
相关资源
最近更新 更多