我正在使用cheerio.js和puppeteer.js,如下tutorial尝试做一些基本的网页抓取。我没有完全按照教程进行操作,因为我试图在服务器端编写它,其想法是让我的后端处理所有抓取,然后将来将该数据传递到前端。
正如现在所写,我得到了
[nodemon] 由于更改而重新启动...
[nodemon] 启动 Node server.js
您的应用程序正在监听端口 8080
[功能]
看起来dynamicScraper
正在返回[Function]
,而我希望它是像教程中那样的html?
主 server.js 文件
'use strict';
const express = require('express');
const cors = require('cors');
const app = express();
const cheerio = require('./potusScraper');
app.use(express.json());
app.use(
cors({
origin: ['http://localhost:3000']
})
);
app.get('/', (req, res) => {
let { scraper, dynamicScraper } = cheerio;
//dynamicScraper should return html as a string?
dynamicScraper()
.then(html => {
res.send(html);
})
.catch(err => {
console.log(err);
});
});
app.listen(process.env.PORT || 8080, () => {
console.log(`Your app is listening on port ${process.env.PORT || 8080}`);
});
potusScraper.js 文件
'use strict';
const rp = require('request-promise');
const $ = require('cheerio');
const puppeteer = require('puppeteer');
const url = 'https://en.wikipedia.org/wiki/List_of_Presidents_of_the_United_States';
const url2 = 'https://www.reddit.com';
const cheerio = {
scraper: function() {
return rp(url)
.then(html => {
const wikiUrls=[];
for (let i = 0; i < 45; i++) {
wikiUrls.push($('big > a', html)[i].attribs.href);
}
return(wikiUrls);
})
.catch(err => console.log(err))
},
dynamicScraper: function() {
return puppeteer //doesn't look like this works?
.launch()
.then(browser => {
return browser.newPage();
})
.then(page => {
return page.goto(url2)
.then(() => {return page.content});
})
.then(html => {
console.log(html);
return(html);
})
.catch(err => console.log(err));
}
}
module.exports = cheerio;
最佳答案
您正在返回 page.content
在此代码行中使用函数而不是调用它:
.then(page => {
return page.goto(url2)
.then(() => {return page.content});
})
第三行应如下所示:
.then(() => {return page.content()});
此外,您可以使用简洁的箭头函数来简化代码:
.then(() => page.content());
关于javascript - 如何使用Puppeteer库抓取动态网页返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55429002/