nodejs提供了很多第三方模块供我们使用,我们只需安装即可,这里推荐安装淘宝的镜像来提高速度,在命令行中输入 npm install -g cnpm --registry=https://registry.npm.taobao.org
即可.
如何使用
- 使用第三方模块首先需要初始化项目,在当前的目录(文件夹名称不能是英文,否则会报错)下执行终端命令
npm init -y
这样会在当前目录下新建一个package.json
的文件用于记录使用了哪些第三方模块并且记录版本号.
接下来以爬虫模块为例演示如何使用第三方模块.
官网文档 爬虫模块文档
- 安装模块 参照官网,第一步我们应该在终端中执行命令
npm install crawler
. 这样会生成node_modules
与package-lock.json
两个文件.
前者会保存第三方模块的文件以及他的依赖包,而后者用于记录每一个包的下载地址以提高更新速度.
- 接下来我们就可以使用安装好的模块了,参照官网
//1.导入模块
var Crawler = require("crawler");
//2.创建爬虫对象
var c = new Crawler({
maxConnections : 10,
// This will be called for each crawled page
callback : function (error, res, done) {
//爬好之后会执行这个回调函数
if(error){
console.log(error);
}else{
//将爬好的数据赋值给juqery对象
var $ = res.$;
// $ is Cheerio by default
//a lean implementation of core jQuery designed specifically for the server
console.log($("html").html());
//使用jquery的语法来解析页面
console.log($('#lg>img').attr('src'));
}
done();
}
});
// Queue just one URL, with default callback
//3.开始爬虫
c.queue('http://www.baidu.com');
接下来被爬取的数据就会在终端中打印出来,以上就是如何导入第三方模块的方法.