欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

nodejs制作小爬蟲功能示例

 更新時(shí)間:2020年02月24日 10:44:11   作者:巴啦啦小能量  
這篇文章主要介紹了nodejs制作小爬蟲功能,結(jié)合實(shí)例形式分析了node.js安裝request、cheerio模塊及請求發(fā)送、數(shù)據(jù)庫操作等相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下

本文實(shí)例講述了nodejs制作小爬蟲功能。分享給大家供大家參考,具體如下:

1 安裝nodejs

2 安裝需要模塊

npm install request cheerio 

3 新建js文件

4 引入

const request=require("request")
const cheerio=require("cheerio")

5 利用request模塊發(fā)送請求

request('http://news.dgut.edu.cn/dgut/xydt/news_list.shtml',function(err,res){
  if(err)
  {
    console.log('請求出錯');
  }
  else
  {
    var $ = cheerio.load(res.body, {decodeEntities: false});
    $('.listList').children('ul').children('li').each(function(){ //找到li元素對象然后通過each遍歷
      var newsTitle = $(this).children('a').text(); //得到<a>標(biāo)簽的文字
      var newsTime= $(this).children('span').eq(1).text();//得到第二個<span>標(biāo)簽的文字
      var newsUrl= "http://news.dgut.edu.cn"+$(this).children('a').attr('href');//得到<a>標(biāo)簽的href的值
    item++;
    console.log("已爬取"+item+"條記錄");
    });
  }
});

一個小爬蟲案例就完了

附上完整代碼

request('http://news.dgut.edu.cn/dgut/xydt/news_list.shtml',function(err,res){
  if(err)
  {
    console.log('請求出錯');
  }
  else
  {
    var $ = cheerio.load(res.body, {decodeEntities: false});
    $('.listList').children('ul').children('li').each(function(){ //找到li元素對象然后通過each遍歷
      var newsTitle = $(this).children('a').text(); //得到<a>標(biāo)簽的文字
      var newsTime= $(this).children('span').eq(1).text();//得到第二個<span>標(biāo)簽的文字
      var newsUrl= "http://news.dgut.edu.cn"+$(this).children('a').attr('href');//得到<a>標(biāo)簽的href的值
    item++;
    console.log("已爬取"+item+"條記錄");
    });
  }
});

下面的帶數(shù)據(jù)庫

const request=require("request")
const cheerio=require("cheerio")
const mysql=require('mysql')
const db=mysql.createPool({host:'120.79.5554',user:'root',password:'root',database:'pachong'});
var item=0;
request('http://news.dgut.edu.cn/dgut/xydt/news_list.shtml',function(err,res){
  if(err)
  {
    console.log('請求出錯');
  }
  else
  {
    var $ = cheerio.load(res.body, {decodeEntities: false});
    $('.listList').children('ul').children('li').each(function(){ //找到li元素對象然后通過each遍歷
      var newsTitle = $(this).children('a').text(); //得到<a>標(biāo)簽的文字
      var newsTime= $(this).children('span').eq(1).text();//得到第二個<span>標(biāo)簽的文字
      var newsUrl= "http://news.dgut.edu.cn"+$(this).children('a').attr('href');//得到<a>標(biāo)簽的href的值
      console.log(newsTitle,newsTime,newsUrl)
      db.query(`INSERT INTO news (newsTitle, newsTime, newsUrl) VALUE('${newsTitle}', '${newsTime}','${newsUrl}')`,function(err,data){
      if(err)
      {
        console.log("數(shù)據(jù)庫連接錯誤");
      }
    })
    item++;
    console.log("已爬取"+item+"條記錄");
    });
  }
});

希望本文所述對大家node.js程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評論