HTML 데이터를 Node.js로 가져오는 방법
axios 라이브러리 사용
const cheerio = require("cheerio");
const axios = require("axios");
const iconv = require("iconv-lite");
//크롤링 주소
const url =
"http://www.yes24.com/24/Category/BestSeller";
const router = express.Router();
router.get("/goods/add/crawling", async (req, res) => {
try {
await axios({
url: url,
method: "GET",
responseType: "arraybuffer",
}).then(async (html) => {
const content = iconv.decode(html.data, "EUC-KR").toString();
//크롤링 코드
});
res.send({ result: "success", message: "크롤링이 완료 되었습니다." });
} catch (error) {
//실패 할 경우 코드
console.log(error)
res.send({ result: "fail", message: "크롤링에 문제가 발생했습니다", error:error });
}
});
한글 깨짐 방지 코드
코드 내용
const content = iconv.decode(html.data, "EUC-KR").toString();
cheerio 사용
const $ = cheerio.load(content);
const list = $("ol li");
await list.each( async (i, tag) => {
**let desc = $(tag).find("p.copy a").text()
let image = $(tag).find("p.image a img").attr("src")
let title = $(tag).find("p.image a img").attr("alt")
let price = $(tag).find("p.price strong").text()**
})
데이터 가공 (비어있는 데이터가 있을때)
if(desc && image && title && price){
price = price.slice(0,-1).replace(/(,)/g, "")
let date = new Date()
let goodsId = date.getTime()
}
크롤링 데이터 DB 저장
if(desc && image && title && price){
price = price.slice(0,-1).replace(/(,)/g, "")
let date = new Date()
let goodsId = date.getTime()
await Goods.create({
goodsId:goodsId,
name:title,
thumbnailUrl:image,
category:"도서",
price:price
})
}