Reputation: 137
I can't use map function in the right way within google apps script while scraping two fields—movie name
and image
— from a webpage.
function scrapeMovies() {
const URL = "https://yts.am/browse-movies";
const response = UrlFetchApp.fetch(URL);
const $ = Cheerio.load(response.getContentText());
const container = $(".browse-movie-wrap");
const result = container.map(item => {
const movieName = $(item).find('a.browse-movie-title').text();
const movieImage = $(item).find('img.img-responsive').attr('src');
console.log(movieName,movieImage);
});
}
When I execute the script, all I get is undefined
as result.
Upvotes: 1
Views: 162
Reputation: 11214
You can still use map
but you need to change the way you access the element.
The reason it is undefined
is because you were trying to do a find
on the index
value. Upon testing, container on each element returns [index, item]
instead of [item, index]
. Specifying you want the 2nd element will fix the issue.
const result = container.map((index, item) => {
const movieName = $(item).find('a.browse-movie-title').text();
const movieImage = $(item).find('img.img-responsive').attr('src');
console.log(movieName, movieImage);
});
But since you aren't returning anything, just use each
as mentioned by Sysix.
result
when using map
and trying to log result
.var result = [];
container.each((index, item) => {
const movieName = $(item).find('a.browse-movie-title').text();
const movieImage = $(item).find('img.img-responsive').attr('src');
result.push([movieName, movieImage]);
});
console.log(result);
Upvotes: 2