node.js 간단 한 파충류 사례 튜 토리 얼 만 들 기
우선 nodejs 를 다운로드 해 야 합 니 다.이 건 괜 찮 을 것 같 습 니 다.
4.567917.원문 은 webstrom 을 다운로드 하 라 고 요구 합 니 다.제 컴퓨터 에 원래 있 지만 다운로드 하지 않 아 도 됩 니 다.완전히 명령 행 에서 조작 하면 됩 니 다프로젝트 생 성
준비 작업 이 끝 났 으 니 다음은 공 사 를 시작 하 겠 습 니 다.
e 판 입장:E:
폴 더 에 들 어가 기:cd my Study Nodejs(당신 이 만 든 폴 더 의 이름)
모두 영문 기호 입 니 다.
프로젝트 를 초기 화 합 니 다.만 든 폴 더 아래 npm init 초기 화 항목 을 실행 합 니 다.
차 로 돌아 가면 마지막 에 yes 를 지면 됩 니 다
만 든 폴 더 의 디 렉 터 리 에서 실행
npm install cheerio Csave
npm install request -save
무 대 를 오 르 려 면 이 두 가방 이면 충분 합 니 다.석류 에 오 르 려 면 인 코딩 을 추가 로 바 꾸 는 가방 이 필요 합 니 다.windows 위 에는...
npm install iconv-lite -save
Mac 위 에 npm install iconv-save.
운행 결 과 는 두 번 째 그림 이 어야 합 니 다.중간 에 손 이 미 끄 러 워 서 알파벳 을 적 게 썼 습 니 다파일 생 성
만 든 폴 더 아래 에 올 라 온 텍스트 데 이 터 를 저장 하기 위해 data 폴 더 를 만 듭 니 다.
그림 데 이 터 를 저장 하기 위해 image 폴 더 를 만 듭 니 다.
프로그램 을 쓰기 위해 js 파일 을 만 듭 니 다.예 를 들 어 study.js.메모 장 파일 을 만 들 고.txt 를.js 로 변경 합 니 다)
Csave 의 목적 은 이 가방 에 대한 의존 도 를 package.json 파일 에 기록 하 는 것 입 니 다
 
  
 무 대 컴퓨터 대학 뉴스 파충류 코드
다음은 무 대 컴퓨터 학원 뉴스의 파충류 코드 입 니 다.만 든.js 파일 에 복사 하여 저장 합 니 다.
var http = require('http');
var fs = require('fs');
var cheerio = require('cheerio');
var request = require('request');
var i = 0;
//  url 
var url = "http://cs.whu.edu.cn/a/xinwendongtaifabu/2018/0428/7053.html"; 
function fetchPage(x) {     //       
  startRequest(x); 
}
function startRequest(x) {
     //  http          get        
     http.get(x, function (res) {     
        var html = '';        //           html  
        var titles = [];    
        res.setEncoding('utf-8'); //      
     //  data  ,       
     res.on('data', function (chunk) {   
	      html += chunk;
	 });
     //  end  ,         html     ,       
     res.on('end', function () {
         var $ = cheerio.load(html); //  cheerio    html
         var news_item = {
          //       
          title: $('div#container dt').text().trim(),
          i: i = i + 1,     
       };
	  console.log(news_item);     //      
	  var news_title = $('div#container dt').text().trim();
	  savedContent($,news_title);  //              
	  savedImg($,news_title);    //              
       //      url
       var nextLink="http://cs.whu.edu.cn" + $("dd.Paging a").attr('href');
       str1 = nextLink.split('-');  //   url     
       str = encodeURI(str1[0]);  
       //      ,    I,           .    8 ,     8
       if (i <= 8) {                
          fetchPage(str);
       }
	});
}).on('error', function (err) {
      console.log(err);
    });
 }
//      :               
function savedContent($, news_title) {
	$('dd.info').each(function (index, item) {
		var x = $(this).text();       
		var y = x.substring(0, 2).trim();
		if (y == '') {
			x = x + '
';   
			//              /data    ,            
			fs.appendFile('./data/' + news_title + '.txt', x, 'utf-8', function (err) {
				if (err) {
				console.log(err);
				}
			});
		}	
	})
}       
//      :              
function savedImg($,news_title) {
  $('dd.info img').each(function (index, item) {
        var img_title = $(this).parent().next().text().trim();  //       
        if(img_title.length>35||img_title==""){
         	img_title="Null";
        }
        var img_filename = img_title + '.jpg';
        var img_src = 'http://cs.whu.edu.cn' + $(this).attr('src'); //     url
		//  request  ,          ,      
		request.head(img_src,function(err,res,body){
		  if(err){
		    console.log(err);
		  }
		});
		request(img_src).pipe(fs.createWriteStream('./image/'+news_title + '---' + img_filename));     //      ,       /image   ,                    。
	})
}
fetchPage(url);      //       
npm news.js
 
 텍스트 자원:
 
 그림 자원:
 
 석류 기술 토론 구 파충류
무 대의 뉴스 를 다 오 르 는 것 은 결코 짜릿 하지 않다.그래서 석류 오 르 기 기술 토론 구역 을 시도 해 보 았 다.그 중 에 몇 가지 문제 에 부 딪 혔 다.
석류 에 오 를 때 http 요청 메시지 헤더 에 User-agent 필드 가 포함 되 어 있어 야 하기 때문에 초기 url 을 다음 과 같이 변경 해 야 합 니 다.
var url = {
	hostname: 'cl.5fy.xyz',
	path: '/thread0806.php?fid=7',
	headers: {
		'Content-Type': 'text/html',
  	//            
  	'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36',  
  }};
/*
* @Author: user
* @Date:   2018-04-28 19:34:50
* @Last Modified by:   user
* @Last Modified time: 2018-04-30 21:35:26
*/
var http = require('http');
var fs = require('fs');
var cheerio = require('cheerio');
var request = require('request');
var iconv=require('iconv-lite');
var i = 0;
  //          
  var temp=0;
  let startPage=3;//       
  let page=startPage;
  let endPage=5;//     
  let searchText='';//      ,      ,      
  //  url 
  var url = {
  hostname: '1024liuyouba.tk',
  path: '/thread0806.php?fid=16'+'&search=&page='+startPage,
  headers: {
    'Content-Type': 'text/html',
    //            
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36',  
  }};
//    url
urlList=[];
//       
function fetchPage(x) { 
  setTimeout(function(){  
    startRequest(x); },5000)
}
//          url
function getUrl(x){
  temp++;
  http.get(x,function(res){
    var html = ''; 
    res.setEncoding('binary');
    res.on('data', function (chunk) {   
      html += chunk;
    });
    res.on('end', function () {
      var buf=new Buffer(html,'binary');
      var str=iconv.decode(buf,'GBK');
          var $ = cheerio.load(str); //  cheerio    html                
          $('tr.tr3 td.tal h3 a').each(function(){
            var search=$(this).text();
            if(search.indexOf(searchText)>=0){
            var nextLink="http://cl.5fy.xyz/" + $(this).attr('href');
            str1 = nextLink.split('-');  //   url     
            str = encodeURI(str1[0]); 
            urlList.push(str); }
          })
          page++;
          if(page<endPage){
            //     url
            x.path='/thread0806.php?fid=16'+'&search=&page='+page,
            getUrl(x);
          }else if(urlList.length!=0){
            fetchPage(urlList.shift());
          }else{
            console.log('       !');
          }
        })
  }).on('error', function (err) {
    console.log(err);
  });
}
function startRequest(x) {
  if(temp===0){
    getUrl(x);     
  }   
  else{
     //  http          get        
     http.get(x, function (res) {     
        var html = '';        //           html  
        res.setEncoding('binary');
        var titles = [];        
	     //  data  ,       
	    res.on('data', function (chunk) {   
	      html += chunk;
	    });
	     //  end  ,         html     ,       
	    res.on('end', function () {
	    	var buf=new Buffer(html,'binary');
	    	var str=iconv.decode(buf,'GBK');
	        var $ = cheerio.load(str); //  cheerio    html
	        var news_item = {
	          	//       
	        	title: $('h4').text().trim(),
	        	//i             
	        	i: i = i + 1,     
	      	};
	    console.log(news_item);     //    
	  	var news_title = $('h4').text().trim();
		
	  	savedContent($,news_title);  //              
		
	  	savedImg($,news_title);    //              
		
	  	//          
	  	if (urlList.length!=0 ) {
	    	fetchPage(urlList.shift());
	  	}
	});
}).on('error', function (err) {
    console.log(err);
  });
 }
}
       //      :               
function savedContent($, news_title) {
	$("div.t2[style] .tpc_content.do_not_catch").each(function (index, item) {
          var x = $(this).text();       
          x = x + '
';   
		  //              /data    ,            
		  fs.appendFile('./data/' + news_title + '.txt', x, 'utf-8', function (err) {
			  if (err) {
			    console.log(err);
			  }
		  });
		})
 }
//      :              
function savedImg($,news_title) {
  //     
    fs.mkdir('./image/'+news_title, function (err) {
        if(err){console.log(err)}
      });
  $('.tpc_content.do_not_catch input[src]').each(function (index, item) {
        var img_title = index;//           
        var img_filename = img_title + '.jpg';
        var img_src = $(this).attr('src'); //     url
//  request  ,          ,      
request.head(img_src,function(err,res,body){
  if(err){
    console.log(err);
  }
});
setTimeout(function(){
  request({uri: img_src,encoding: 'binary'}, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      fs.writeFile('./image/'+news_title+'/' + img_filename, body, 'binary', function (err) {
        if(err){console.log(err)}
      });
    }
  })
});
})
}
fetchPage(url);      //       
 
 node.js 가 간단 한 파충류 사례 튜 토리 얼 을 만 드 는 것 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 node.js 가 간단 한 파충류 콘 텐 츠 를 만 드 는 것 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 찾 아 보 세 요.앞으로 많은 응원 부탁드립니다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Express + AWS S3 이미지 업로드하기웹 사이트 및 모바일 애플리케이션 등에서 원하는 양의 데이터를 저장하고 보호할 수 있다. 데이터에 대한 액세스를 최적화, 구조화 및 구성할 수 있는 관리 기능을 제공한다. AWS S3 에 저장된 객체에 대한 컨테이너...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.