import axios from "axios" import cheerio from "cheerio"; import express from 'express' import request from 'request' const app = express() // axios를 활용해 AJAX로 HTML 문서를 가져오는 함수 구현 // getHTML 함수 실행 후 데이터에서 // body > main > div > section > ul > li > article > h2 > a // 에 속하는 제목을 titleList에 저장 app.get('/', (req, res) => { const url = "https://www.naver.com/" request(url, function (err, res, html) { // console.log(html) if (!err) { let resultArr = []; let $ = cheerio.load(html, null, false); // false 넣으면 헤더같은 거 없애고 null은 속성넣어줄 수 있음. let colArr = $(".list_theme_wrap")//가져올 클래스 넣기 for (let i = 0; i < colArr.length; i++) { resultArr.push(colArr[i].children[1].attribs.title) } console.log(resultArr) } } // .then(html => { // let titleList = []; // const $ = cheerio.load(html.data); // // ul.list--posts를 찾고 그 children 노드를 bodyList에 저장 // const bodyList = $(".title_post > span"); // // bodyList를 순회하며 titleList에 h2 > a의 내용을 저장 // bodyList.each(function (i, elem) { // titleList[i] = { // title: $(this) // .text() // }; // }); // return titleList; // }) // .then(res => console.log(res)); // 저장된 결과를 출력 ) }) app.listen(3001, () => { console.log('Server is listening on port 3001') })