const { extractData } = require("./actions");
const { request, setOption } = require("./help");
const scrapFKByKeyword = async (keyword) => {
try {
const options = setOption(keyword, "keyword");
const $ = await request(options);
//검색하면 전면에 뜨는 페이지를 스크래핑
const curPage = await getMainPageContents($);
//나머지 페이지 스크래핑
const otherPages = await Promise.all(
$("fieldset > a")
.toArray()
.map((el) => {
const page = getOtherPagesContents($(el).attr("href"));
return page;
})
);
// // 전면 페이지와 나머지 페이지를 하나의 배열로 합침
const result = curPage.concat(...otherPages);
console.log(result);
// return result;
} catch (e) {
console.log(e);
}
};
const getMainPageContents = async ($) => {
try {
return await extractData($);
} catch (error) {
console.error(error);
}
};
const getOtherPagesContents = async (string) => {
//method는 "keyword"와 "href"이 있음. 검색어로 나온 첫번째 페이지는 keyword로, 나머지 page들은 url을 사용해서 긁어오기
try {
const options = setOption(string, "href");
const $ = await request(options);
return await extractData($);
} catch (error) {
console.error(error);
}
};
scrapFKByKeyword("애플워치");
코드를 매우 많이 바꾸어서 이런식으로 나오게 되었다.
const extractData = async ($) => {
const result = [];
for (let el of $(".li_best2_pop0").toArray()) {
let obj = {
title: $(el).find("a.hotdeal_var8").text().trim(),
date: $(el).find("span.regdate").text().trim(),
author: $(el).find("span.author").text().slice(3),
//view를 제외하면 모든 페이지가 잘 불러와짐
//depth를 하나 들어가면 바로 멈춰짐
// view: await getView($, $(el).find(".hotdeal_var8").attr("href")),
};
result.push(obj);
}
return result;
};
promise를 사용하는 과정에서
promise.all
의 배열 내에 객체인 요소가 또 비동기 요청을 하면,promise.all
이 작동하지 않는 것을 배웠다.따라서 위 코드처럼
for문
으로 바꿔주었다.