오늘은 alsotang의 크롤러 튜토리얼을 배우고, CNode의 간단한 크롤링을 따라해보겠습니다.
craelr-demo 프로젝트 만들기
먼저 Express 프로젝트를 생성한 후, 당분간 웹에 콘텐츠를 표시할 필요가 없기 때문에 app.js 파일의 모든 콘텐츠를 삭제합니다. 물론 빈 폴더에서 직접 npm install express
필요한 Express 기능을 사용할 수도 있습니다.
타겟사이트 분석
그림에 표시된 것처럼 이는 CNode 홈페이지에 있는 div 태그의 일부입니다. 이 일련의 ID와 클래스를 사용하여 필요한 정보를 찾습니다.

슈퍼에이전트를 사용하여 소스 데이터 획득
superagent는 ajax API에서 사용하는 Http 라이브러리입니다. 사용법은 jQuery와 유사합니다. 이를 통해 get 요청을 시작하고 결과를 콜백 함수에 출력합니다.
var express = require('express');
var url = require('url'); //파싱 작업 url
var superagent = require('superagent'); //이 세 가지 외부 종속성에 대해 npm install
을 잊지 마세요.
var Cherio = require('cheerio');
var eventproxy = require('eventproxy');
var targetUrl = 'https://cnodejs.org/';
superagent.get(targetUrl)
.end(함수(err, res) {
console.log(res);
});
res 결과는 대상 URL 정보를 포함하는 객체이며, 웹사이트 콘텐츠는 주로 텍스트(문자열)로 구성됩니다.

cherio를 사용하여 구문 분석
cheerio는 먼저 .load()를 사용하여 HTML을 로드한 다음 CSS 선택기를 통해 요소를 필터링합니다.
var $ =cherio.load(res.text);
//CSS 선택기를 통해 데이터 필터링
$('#topic_list .topic_title').each(함수 (idx, 요소) {
console.log(요소);
});
결과는 개체입니다. .each(function(index, element))
함수를 호출하여 각 개체를 탐색하고 HTML DOM 요소를 반환합니다.

console.log($element.attr('title'));
을 출력한 결과는 广州 2014年12月06日 NodeParty 之 UC 场
입니다.
console.log($element.attr('href'));
같은 제목은 /topic/545c395becbcb78265856eb2
같은 URL로 출력됩니다. 그런 다음 NodeJS1의 url.resolve() 함수를 사용하여 완전한 URL을 완성합니다.
superagent.get(tUrl)
.end(함수(err, res) {
만약 (오류) {
return console.error(err);
}
var topicUrls = [];
var $ =cherio.load(res.text);
//홈페이지의 모든 링크 가져오기
$('#topic_list .topic_title').each(함수 (idx, 요소) {
var $element = $(요소);
var href = url.resolve(tUrl, $element.attr('href'));
console.log(href);
//topicUrls.push(href);
});
});
eventproxy를 사용하여 각 주제의 콘텐츠를 동시에 크롤링
튜토리얼에서는 깊게 중첩된(직렬) 메서드와 카운터 메서드의 예를 보여줍니다. Eventproxy는 이벤트(병렬) 메서드를 사용하여 이 문제를 해결합니다. 모든 크롤링이 완료되면 eventproxy가 이벤트 메시지를 수신하고 자동으로 처리 기능을 호출합니다.
//1단계: eventproxy 인스턴스 가져오기
var ep = 새 이벤트 프록시();
//2단계: 이벤트 수신을 위한 콜백 함수를 정의합니다.
//After 메소드는 반복 모니터링
//params: 이벤트명(String) 이벤트명, times(Number) 청취횟수, 콜백 콜백함수
ep.after('topic_html', topicUrls.length, function(topics){
// topic은 ep.emit('topic_html', pair)의 40개 쌍
을 40번 포함하는 배열입니다.
//.지도
주제 = topic.map(function(topicPair){
//cherio 사용
var topicUrl = topicPair[0];
var topicHtml = topicPair[1];
var $ =cherio.load(topicHtml);
반품({
제목: $('.topic_full_title').text().trim(),
href: topicUrl,
댓글 1: $('.reply_content').eq(0).text().trim()
});
});
//결과
console.log('결과:');
console.log(주제);
});
//3단계: 이벤트 메시지를 해제하는
결정
topicUrls.forEach(함수 (topicUrl) {
Superagent.get(topicUrl)
.end(함수 (err, res) {
console.log('fetch ' topicUrl '성공');
ep.emit('topic_html', [topicUrl, res.text]);
});
});
결과는 다음과 같습니다

연장훈련(챌린지)
메시지 사용자 이름 및 포인트 받기

기사 페이지의 소스 코드에 댓글을 남긴 사용자의 클래스 이름을 찾으세요. 클래스 이름은 reply_author입니다. console.log $('.reply_author').get(0)
의 첫 번째 요소에서 볼 수 있듯이 우리가 얻어야 할 모든 것이 여기에 있습니다.

먼저 기사를 크롤링하여 필요한 모든 것을 한 번에 가져오겠습니다.
var userHref = url.resolve(tUrl, $('.reply_author').get(0).attribs.href);
console.log(userHref);
console.log($('.reply_author').get(0).children[0].data);
https://cnodejs.org/user/username
을 통해 포인트 정보를 캡쳐할 수 있습니다.
$('.reply_author').each(함수 (idx, 요소) {
var $element = $(요소);
console.log($element.attr('href'));
});
사용자 정보 페이지 $('.big').text().trim()
에 포인트 정보가 있습니다.
cherio의 함수 .get(0)을 사용하여 첫 번째 요소를 가져옵니다.
var userHref = url.resolve(tUrl, $('.reply_author').get(0).attribs.href);
console.log(userHref);
기사 1개를 캡쳐한 것인데 아직 수정해야 할 내용이 40개나 있습니다.