[Edited] I wanna create node js scraper. Thanks for Shubham Khatri helping! But i get new suggestion, i trying get ‘value’ from ‘.then’ and it send me ‘value is not defined’. Please says me how to fix this? I trying and don’t find how to fix this!
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("Price today is:" + value));
const BuyPrice = value
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.
>Solution :
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