javascript - Cheerio 使用离子创建 API
问题描述
我正在创建一个离子应用程序。我正在使用 Cheerio 和 Node.js 来抓取网站。我无法将整个数组返回到本地主机,它只返回第一个对象。我怎样才能返回整个数组?
这是抓取代码(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}`);
});
解决方案
如果发布的代码是您的代码的总和,那么问题可能是缺少结束标签。它应该如下图所示:
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;
推荐阅读
- php - 为什么 AJAX 在 WordPress 函数中运行两次
- java - 如何在调用父构造函数之前覆盖子类中的父类属性?
- jquery - jQuery多次调用click
- android - 需要让我的启动画面适合所有设备吗?
- excel - 在excel中从给定范围的行中查找常见行
- c# - Xamarin Forms CollectionView ScrollTo 在外部调用时
- python - 使用过去 24 小时的总和创建新列
- html - 当父级具有弹性方向时如何强制弹性项目不换行:列
- amazon-web-services - AWS Lambda:发送 POST 消息时出现键错误
- ios - Apple 分发证书缺少私钥