用户登录
用户注册

分享至

nodejs制作小爬虫功能示例

  • 作者: 许狰狞
  • 来源: 51数据库
  • 2021-08-29

本文实例讲述了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+"条记录");
    });
  }
});

希望本文所述对大家node.js程序设计有所帮助。

软件
前端设计
程序设计
Java相关