NodeJS概述2-事件插件-簡易爬蟲

事件 events 模塊
原生事件寫法php

/* 
    * 1. 事件分類
      * DOM0級 事件  - on + eventType
      * DOM2級 事件  - 事件監聽
    * 2. 事件構成部分有哪些?    dom.onclick = function () {}
      * 事件源
      * 事件類型  click change ... 
      * 事件處理程序
    * 3. 事件綁定形式有哪些?
      *  dom.onclick = function () {}
      * 事件監聽   dom.addEventListener('click',function(){},false)
      * 元素綁定 <div onclick = "load()"></div>
  */

Node.js 事件驅動html

  1. 問題: Node.js中有DOM嗎?
    • 沒有
    • 結論: 原生js DOM 事件都不能用
  2. 建立了一個叫作 events 內置模塊來解決這個問題
const events= require('events');
//events.EventEmitter//構造函數
console.log(events.EventEmitter.prototype)//原型鏈
/* 
 EventEmitter {
    _events: undefined,
    _eventsCount: 0,
    _maxListeners: undefined,
    setMaxListeners: [Function: setMaxListeners],
    getMaxListeners: [Function: getMaxListeners],
    emit: [Function: emit],
    addListener: [Function: addListener],
    on: [Function: addListener],
    prependListener: [Function: prependListener],
    once: [Function: once],
    prependOnceListener: [Function: prependOnceListener],
    removeListener: [Function: removeListener],
    off: [Function: removeListener],
    removeAllListeners: [Function: removeAllListeners],
    listeners: [Function: listeners],
    rawListeners: [Function: rawListeners],
    listenerCount: [Function: listenerCount],
    eventNames: [Function: eventNames]
  }
*/
const archetype=events.EventEmitter.prototype;
// archetype.on(事件,事件處理函數)  做用發佈
// archetype.emit(事件名,實際參數)     做用訂閱
archetype.on('handler',(val)=>{
console.log('事件觸發',val);
})
archetype.emit('handler',111)

Readline模塊逐行讀取文本內容
readline 模塊提供了一個接口,用於一次一行地讀取可讀流(例如 process.stdin)中的數據。web

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question('你如何看待 Node.js 中文網?', (answer) => {
  // TODO:將答案記錄在數據庫中。
  console.log(`感謝您的寶貴意見:${answer}`);

  rl.close();
});
const readline = require('readline');
const fs = require('fs');

const rl = readline.createInterface({
  input: fs.createReadStream('sample.txt')
});

rl.on('line', (line) => {
  console.log('Line from file:', line);
});

簡易爬蟲數據庫

/* 
  * 爬蟲
    * 1. 進行數據請求,獲取網頁內容       http
    * 2. 進行數據分析、數據清洗 
    * 3. 發送給咱們本身的網頁
*/
const http=require('http')
//獲取 JSON 的示例:
http.get('http://jsonplaceholder.typicode.com/albums', (res) => {
     /* res就是我獲得的返回值 */
  const { statusCode } = res;//狀態碼
  const contentType = res.headers['content-type'];//獲得的文件類型
// 錯誤代碼處理
  let error;
  if (statusCode !== 200) {
    error = new Error('請求失敗\n' +
                      `狀態碼: ${statusCode}`);
  } else if (!/^application\/json/.test(contentType)) {
    error = new Error('無效的 content-type.\n' +
                      `指望的是 application/json 但接收到的是 ${contentType}`);
  }
  if (error) {
    console.error(error.message);
    // 消費響應數據來釋放內存。
    res.resume();//從新發起數據
    return;
  }

  res.setEncoding('utf8');//中文編碼
  let rawData = '';//真實數據
  res.on('data', (chunk) => { rawData += chunk; });// 經過data事件將數據分片,而後逐片添加到rawData身上,好處就是當咱們執行每個分片的小任務時,至少給其餘任務提供了可執行的機會
  res.on('end', () => {//結束
    try {// 高級編程 錯誤捕獲
      const parsedData = JSON.parse(rawData);
      console.log(parsedData);
    } catch (e) {
      console.error(e.message);
    }
  });
}).on('error', (e) => {
  console.error(`出現錯誤: ${e.message}`);
});
const http=require('http');
const cheerio=require('cheerio')
const options={
    hostname: 'jx.1000phone.net',
  port: 80,
  path: '/teacher.php/Class/classDetail/param/rqiWlsefmajGmqJhXXWhl3ZiZ2Zn',
  method: 'GET',
  headers: {
    Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
    'Cache-Control': 'no-cache',
    Connection: 'keep-alive',
    Cookie: 'PHPSESSID=ST-117984-IVZSfYMlr9YXvRfFRm-A1TimOeA-izm5ejd5j1npj2pjc7i3v4z',
    Host: 'jx.1000phone.net',
    Pragma: 'no-cache',
    Referer: 'http://jx.1000phone.net/teacher.php/Class/index',
    'Upgrade-Insecure-Requests': 1,
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': 0
  }}

http.get(options, (res) => {
  const { statusCode } = res;
  const contentType = res.headers['content-type'];


  res.setEncoding('utf8');
  let rawData = '';
  res.on('data', (chunk) => { rawData += chunk; });
  res.on('end', () => {
    try {
const $=cheerio.load(rawData);
$('.student a').each(function(item,index){
    console.log($(this).text());
    
})
      
    } catch (e) {
      console.error(e.message);
    }
  });
}).on('error', (e) => {
  console.error(`出現錯誤: ${e.message}`);
});
相關文章
相關標籤/搜索