所以我正在抓取一个网站,我希望它向innerHTML 显示数据,但我在让它工作时遇到了困难。我正在尝试使用document.getElementById('results').innerHTML = searchJobs('');但它告诉我文档未定义,对不起,这是个菜鸟问题,但问起来比在同一件事上停留 45 分钟更容易。这是代码:function searchJobs(i) { const url = axios.get('actualurl') return fetch(`${url}${i}`) .then(response => response.text()) .then(res => { const jobs = []; const jobsBody = []; const $ = cheerio.load(res.data); $('.result').each((index, element) => { const title = $(element).children('.title').text(); const linkToJob = $(element).children('.title').children('a').attr('href') const body = $(element).children('.summary').text(); jobs[index] = { title, linkToJob, body }; }); return jobs; });}document.getElementById('results').innerHTML = searchJobs('');module.exports = searchJobs;我可以将抓取工具发送到 console.log 就好了。索引路线:const express = require('express');const router = express.Router();const scraper = require('../scrapers/scrapers');/* GET home page. */router.get('/', function(req, res, next) { res.render('index', { title: 'Express' });});应用程序.js:const express = require('express'), path = require('path'), cookieParser = require('cookie-parser'), logger = require('morgan'), puppeteer = require('puppeteer'), axios = require('axios'), cheerio = require('cheerio');es6Renderer = require('express-es6-template-engine');var indexRouter = require('./routes/index');var usersRouter = require('./routes/users');var app = express();// view engine setupapp.engine('html', es6Renderer);app.set('views', './views');app.set('view engine', 'html');app.use(logger('dev'));app.use(express.json());app.use(express.urlencoded({ extended: false }));app.use(cookieParser());app.use(express.static(path.join(__dirname, 'public')));app.use('/', indexRouter);app.use('/users', usersRouter);
1 回答
一只萌萌小番薯
TA贡献1795条经验 获得超7个赞
我想我明白你想要实现的目标。从 scrapers.js 中删除该document.getElementById行并修改其他行,如下所示:
索引路线:
router.get('/', function(req, res, next) {
res.render('index', { locals: { results: scraper.searchJobs() }});
});
看法:
<body>
<p id="results">${results}</p>
</body>
通过这样做,您可以在节点内的服务器上运行抓取工具,然后使用模板引擎将结果呈现为 HTML,然后再将其发送到浏览器。
- 1 回答
- 0 关注
- 74 浏览
添加回答
举报
0/150
提交
取消