温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

nodejs制作小爬虫功能示例

发布时间:2020-09-23 20:21:10 来源:脚本之家 阅读:105 作者:巴啦啦小能量 栏目:web开发

本文实例讲述了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程序设计有所帮助。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI