nodejs简易爬虫
使用nodejs实现简易爬虫主要会使用到三个nodejs包
一、先来简单介绍一下这三个包
1. superagent
- superagent: 主要是用在服务端发送 http 或者 https
2.cheerio
- cheerio : 把页面解析,并返回一个类似于 jQuery 选择器一样的函数
3.fs
- fs : 这个包是node自带的一个包,无需下载直接饮用即可,主要是用来操作文件和文件夹的
二、下面使用者三个包完成某电商网站数据的简单爬取
1. 下载 superagent包和 cheerio包
npm i superagent cheerio
2. 导入包,并设置一个空数组 goodsList 来接收数据
const superagent = require('superagent')
const cheerio = require('cheerio')
const fs = require('fs')
const goodsList = []
3. 使用 superagent 去访问你要爬取的页面
end() 方法就是访问地址结束的回调函数
superagent
.get('https://list.jd.com/list.html?cat=670%2C671%2C672&go=0')
.end((err, data) => {
if (err) return console.log('爬取页面失败')
// data.text 就是整个页面文件
console.log(data.text)
})
使用控制台运行该node 文件结果如图所指示
- 运行指令(你电脑配置有nodejs 环境 并且改命令执行在你操作的的文件夹位置处)
node 你的文件名
4.设置parseData函数对返回的页面进行操作, 并使用 cheerio 进行解析
- 使用 cheerio.load(你要解析的内容) 方法
- 返回值: 就是一个向 $ 函数一样的东西
- 接下来就是在你想要操作的网页找到对应商品元素的类名
- 通过each 遍历所有元素 通过find方法找到你想要的操作的数据
- 将遍历的每个元素的信息push到goodsList数组中去
- 这样最后goodsList就会变成存储着数据的数组对象,方便下一步操作
代码
const superagent = require('superagent')
const cheerio = require('cheerio')
const fs = require('fs')
const goodsList = []
superagent
.get('https://list.jd.com/list.html?cat=670%2C671%2C672&go=0')
.end((err, data) => {
if (err) return console.log('爬取页面失败')
// data.text 就是整个页面文件
parseData(data.text)
})
function parseData(page) {
const $ = cheerio.load(page)
$('.gl-warp > .gl-item').each((index, item) => {
const obj = {
goods_img: $(item).find('img').prop('src'),
goods_price: $(item).find('.p-price i').text(),
goods_title: $(item).find('.p-name i').text(),
goods_name: $(item).find('.p-name em').text()
}
goodsList.push(obj)
})
console.log(goodsList)
}
运行结果
五、最后一步 使用fs实现数据的转存,转存到另外一个json文件
fs.writeFile('./goods_list.json', JSON.stringify(goodsList), () => console.log('写入完成'))
实现效果
- 世界生成会是一行的数据
格式化后的效果就是这样,也就是熟悉的JSON数据格式
完整代码:
const superagent = require('superagent')
const cheerio = require('cheerio')
const fs = require('fs')
const goodsList = []
superagent
.get('https://list.jd.com/list.html?cat=670%2C671%2C672&go=0')
.end((err, data) => {
if (err) return console.log('爬取页面失败')
// data.text 就是整个页面文件
parseData(data.text)
})
function parseData(page) {
const $ = cheerio.load(page)
$('.gl-warp > .gl-item').each((index, item) => {
const obj = {
goods_img: $(item).find('img').prop('src'),
goods_price: $(item).find('.p-price i').text(),
goods_title: $(item).find('.p-name i').text(),
goods_name: $(item).find('.p-name em').text()
}
goodsList.push(obj)
})
console.log(goodsList)
fs.writeFile('./goods_list.json', JSON.stringify(goodsList), () => console.log('写入完成'))
}
==声明:== 本博客不涉及任何商业问题,只是对自己学习的一些简单记录,如有涉及法律问题,请提醒博主,博主自行删除。