国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

nodejs制作小爬蟲功能示例

2024-05-06 15:44:49
字體:
來源:轉載
供稿:網友

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

1 安裝nodejs

2 安裝需要模塊

npm install request cheerio 

3 新建js文件

4 引入

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

5 利用request模塊發送請求

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>標簽的文字      var newsTime= $(this).children('span').eq(1).text();//得到第二個<span>標簽的文字      var newsUrl= "http://news.dgut.edu.cn"+$(this).children('a').attr('href');//得到<a>標簽的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>標簽的文字      var newsTime= $(this).children('span').eq(1).text();//得到第二個<span>標簽的文字      var newsUrl= "http://news.dgut.edu.cn"+$(this).children('a').attr('href');//得到<a>標簽的href的值    item++;    console.log("已爬取"+item+"條記錄");    });  }});

下面的帶數據庫

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>標簽的文字      var newsTime= $(this).children('span').eq(1).text();//得到第二個<span>標簽的文字      var newsUrl= "http://news.dgut.edu.cn"+$(this).children('a').attr('href');//得到<a>標簽的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("數據庫連接錯誤");      }    })    item++;    console.log("已爬取"+item+"條記錄");    });  }});            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 五河县| 昭平县| 泊头市| 满洲里市| 平舆县| 宜丰县| 望江县| 淮安市| 九寨沟县| 丁青县| 金门县| 彝良县| 乌兰浩特市| 任丘市| 崇明县| 同心县| 白河县| 镇安县| 林州市| 罗江县| 陈巴尔虎旗| 永宁县| 武穴市| 西乌珠穆沁旗| 上蔡县| 青河县| 新化县| 桐城市| 福鼎市| 哈密市| 蓬溪县| 独山县| 赤城县| 蒙城县| 怀远县| 固原市| 大同市| 伽师县| 天津市| 湘潭县| 旬阳县|