selenium 모듈을 이용해 크롬창을 띄워 검색해 블로그에 들어가며 블로그 제목을 긁어오고, cheerio 모듈을 이용해 다른 사이트의 DOM을 긁어오는 크롤링을 해봤다.
// selenium 모듈을 이용해 네이버에서 강아지 검색후 첫번째 블로그를 클릭하는 코드
const { Builder, By, Key, until } = require("selenium-webdriver");
(async function test() {
let driver = await new Builder().forBrowser("chrome").build();
try {
await driver.get("https://www.naver.com"); // 네이버 접속
await driver.findElement(By.name("query")).sendKeys("강아지", Key.ENTER); // 네이버 검색창의 class가 query인데, query를 찾아 강아지를 입력한 후 엔터를 눌러 검색한다.
await driver.wait(until.elementLocated(By.css("#header_wrap")), 10000); // 검색후 로딩이 되야하므로 #header_wrap가 리턴될때까지 1초간 기다린다.
let resultElements = await driver.findElements(By.className("total_tit")); // class가 total_tit인 요소를 찾는다. (블로그 제목)
for (let i = 0; i < resultElements.length; i++) {
// 콘솔에 블로그제목이 찍힌다.
console.log("??", await resultElements[i].getText());
}
if (resultElements.length > 0) {
await resultElements[0].click(); // 첫번째 블로그를 클릭해 블로그에 접속한다.
}
try {
await driver.wait(() => {
return false;
}, 4000); // 4초간 크롬창이 켜진채로 유지한후,
} catch (err) {}
} finally {
await driver.quit(); // 크롬창을 종료한다.
}
})();
// cheerio 모듈을 이용해 html 태그 요소들 가져오는 코드
const cheerio = require("cheerio");
const axios = require("axios");
const getHtml = async () => {
try {
return await axios.get("https://www.yna.co.kr/sports/all"); // 가져오고자하는 내용이있는 사이트에 get 요청을해 return값으로 준다.
} catch (error) {
console.error(error);
}
};
getHtml().then((html) => {
let ulList = [];
const $ = cheerio.load(html.data); // getHtml의 return값의 data를 변수 $에 담아
const $bodyList = $("div.list-type038 ul.list").children("li"); // 클레스가 list-type038인 div태그를 찾고 자식중 클레스가 list인 ul을 찾고, 그 자식인 li태그를 $bodyList변수에 담는다.
// const $bodyList = $("div.list-type038 ul.list li"); 도 가능하다.
$bodyList.each(function (i, elem) {
ulList[i] = {
title: $(this).find("strong.tit-news").text(), // li자식중 strong태그의 class tit-news를 찾아 text만 뽑아(?) title의 값으로 넣어준다.
url: $(this).find("figure.img-con a").attr("href"), // figure태그의 class img-con의 자식 a태그를 찾아 a태그의 href의 url을 키 url의 값으로 넣어준다.
image_url: $(this).find("figure.img-con a img").attr("src"), // 위의 a태그 자식인 img태그의 src값을 image_url의 값으로 넣어준다.
image_alt: $(this).find("figure.img-con a img").attr("alt"), // 위의 img태그의 alt값을 image_alt의 값으로 넣어준다.
date: $(this).find("span.txt-time").text(), // span태그의 class txt-time의 텍스트를 date의 값으로 넣어준다.
};
});
console.log(ulList); // 콘솔에 데이터가 찍힌다.
return ulList;
});