>  기사  >  웹 프론트엔드  >  노드 아래 http 크롤러의 샘플 코드 공유

노드 아래 http 크롤러의 샘플 코드 공유

小云云
小云云원래의
2018-01-13 09:10:071406검색

이 글은 주로 node 기반의 http 크롤러의 샘플 코드를 소개하는데, 편집자는 꽤 좋다고 생각해서 공유하고 참고하겠습니다. 편집자를 따라 살펴보겠습니다. 모두에게 도움이 되기를 바랍니다.

잠을 자든 안 자든 매 순간 인터넷, 고객 서비스에서 서버로, 서버에서 서버로 엄청난 양의 데이터가 오고 갈 것입니다. http의 가져오기 및 요청에 의해 완료되는 역할은 데이터를 얻고 제출하는 것입니다. 다음으로 초보자 튜토리얼에서 노드에 관한 장의 코스 인터페이스를 크롤링하기 위한 간단한 작은 크롤러를 작성하기 시작합니다.

Node.js 튜토리얼 홈 페이지의 모든 데이터를 크롤링합니다

node-http.js를 생성합니다. 코드는 다음과 같습니다. 코드에 자세한 설명이 있으므로 직접 이해하실 수 있습니다


var http=require('http');//获取http模块
var url='/nodejs/nodejs-tutorial.html';//定义node官网地址变量

http.get(url,function(res){
  var html='';

  // 这里将会触发data事件,不断触发不断跟新html直至完毕
  res.on('data',function(data){
    html +=data
  })

  // 当数据获取完成将会触发end事件,这里将会打印初node官网的html
  res.on('end',function(){
    console.log(html)
  })
}).on('error',function(){
  console.log('获取node官网相关数据出错')
})

터미널 실행 결과에서 발견됨 이 페이지의 모든 HTML이 크롤링되었습니다.


G:\node\node-http> node node-http.js
<!Doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta property="qc:admins" content="465267610762567726375" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Node.js 教程 | 菜鸟教程</title>
<link rel=&#39;dns-prefetch&#39; href=&#39;//s.w.org&#39; />
<link rel="canonical" href="http://www.php.cn/nodejs/nodejs-tutorial.html" />
<meta name="keywords" content="Node.js 教程,node,Node.js,nodejs">
<meta name="description" content="Node.js 教程  简单的说 Node.js 就是运行在服务端的 JavaScript。 Node.js 是一个基于Chrome JavaScript 运行时建立的一个平台
。 Node.js是一个事件驱动I/O服务端JavaScript环境,基于Google的V8引擎,V8引擎执行Javascript的速度非常快,性能非常好。  谁适合阅读本教程? 如果你是一个前端程序员,你不懂得像PHP、Python或Ruby等动态编程语言,..">
<link rel="shortcut icon" href="//static.runoob.com/images/favicon.ico" rel="external nofollow" rel="external nofollow" mce_href="//static.runoob.com/images/favicon.ico" rel="external nofollow" rel="external nofollow" type="image/x-icon">
<link rel="stylesheet" href="/wp-content/themes/runoob/style.css?v=1.141" rel="external nofollow" type="text/css" media="all" />
<link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="external nofollow" media="all" />
<!--[if gte IE 9]><!-->
。。。。。。。。。。
这里只展示部分不然你半天看不到头

물론 HTML 크롤링은 우리에게 쓸모가 없습니다. 예를 들어, 다음과 같습니다. 노드 튜토리얼, 내가 선택할 수 있도록 코스 카탈로그가 무엇인지 알고 싶습니다. 관심이 있다면 가서 살펴보고 배우십시오. 코드로 곧장 가보겠습니다:

하지만 그 전에 Cheerio 모듈을 다운로드해야 합니다. (cheerio는 nodejs의 페이지 크롤링 모듈로, 서버에 맞게 특별히 맞춤화된 빠르고 유연하며 구현된 jQuery 코어 구현입니다. 다양한 웹 크롤러 프로그램에 적합합니다. . ) 자세한 소개를 직접 검색할 수 있습니다.


PS G:\node\node-http> npm install cheerio

node-http-more.js를 생성하세요. 코드는 다음과 같습니다:


var http=require(&#39;http&#39;);//获取http模块
var cheerio=require(&#39;cheerio&#39;);//引入cheerio模块
var url=&#39;http://www.php.cn/nodejs/nodejs-tutorial.html&#39;;//定义node官网地址变量
// filer node chapter
function filerNodeChapter(html){
  // 将爬取得HTML装载起来
  var $=cheerio.load(html);
  // 拿到左侧边栏的每个目录
  var nodeChapter=$(&#39;#leftcolumn a&#39;);
  //这里我希望我能获取的到的最终数据格式这个样子的,如此我们能知道每个目录的地址及标题
  /**
   * [{id:,title:}]
   */
  var chapterData=[];
  nodeChapter.each(function(item){
    // 获取每项的地址及标题
    var id=$(this).attr(&#39;href&#39;);
    var title=$(this).text();
    chapterData.push({
      id:id,
      title:title
    })
  })

  return chapterData;

}

//获取每个数据
function getChapterData(nodeChapter){
  nodeChapter.forEach(function(item){
    console.log(&#39; 【 &#39;+item.id+&#39; 】&#39;+item.title+&#39;\n&#39;)
  });
}

http.get(url,function(res){
  var html=&#39;&#39;;

  // 这里将会触发data事件,不断触发不断跟新html直至完毕
  res.on(&#39;data&#39;,function(data){
    html +=data
  })

  // 当数据获取完成将会触发end事件,这里将会打印初node官网的html
  res.on(&#39;end&#39;,function(){
    //console.log(html)
    // 过滤出node.js的课程目录
    var nodeChapter= filerNodeChapter(html);

    //循环打印所获取的数据
    getChapterData(nodeChapter)
  })
}).on(&#39;error&#39;,function(){
  console.log(&#39;获取node官网相关数据出错&#39;)
})

터미널 실행 결과 및 강좌 디렉터리를 인쇄하세요


G:\node\node-http> node node-http-more.js
 【 /nodejs/nodejs-tutorial.html 】
Node.js 教程

 【 /nodejs/nodejs-install-setup.html 】
Node.js 安装配置

 【 /nodejs/nodejs-http-server.html 】
Node.js 创建第一个应用

 【 nodejs-npm.html 】 NPM 使用介绍

 【 nodejs-repl.html 】 Node.js REPL

 【 nodejs-callback.html 】 Node.js 回调函数

 【 nodejs-event-loop.html 】 Node.js 事件循环

 【 nodejs-event.html 】 Node.js EventEmitter

 【 nodejs-buffer.html 】 Node.js Buffer

 【 nodejs-stream.html 】 Node.js Stream

 【 /nodejs/nodejs-module-system.html 】
Node.js 模块系统
。。。。。。。。。。。
这里就不全部给出,你可以自己尝试着运行操作查看所有结果

관련 권장 사항:

Node. Node.js 크롤러 웹페이지 요청 모듈에 대한 자세한 설명

Node.js 정보 크롤러 개발 과정 코드 공유

NodeJS 백과사전 크롤러 예제 튜토리얼

위 내용은 노드 아래 http 크롤러의 샘플 코드 공유의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.