I wanna create node js scraper. But if i try using my finished scraper in function. Print 'undefined'. Please help me!
const axios = require('axios')
const cheerio = require('cheerio')
const url = 'XXX'
GetInfo = function() {
axios.get(url)
.then(response => {
const Response = response.data
const $ = cheerio.load(Response)
const text = $('span.bookbuy').text()
return text;
})
}
console.log(GetInfo())
I try add to my scraper return, and says undefined, and i don't know what to need to add, to make it work. I created scraper to get info of price book, if there is a discount, i go to buy this book.
CodePudding user response:
axios call is async and it returns a promise which is resolved when the call has returned a response or an error.
Since the console log is executed before the promise has resolved, you don't see the result you expect.
To log the returned value you need to use the .then
function on the returned promise
const axios = require('axios')
const cheerio = require('cheerio')
const url = 'XXX'
GetInfo = function() {
return axios.get(url)
.then(response => {
const Response = response.data
const $ = cheerio.load(Response)
const text = $('span.bookbuy').text()
return text;
})
}
GetInfo().then((value) => console.log(value));
Read more about Promises and async calls here