Nodejs简易小爬虫

使用node访问jd的笔记本电脑列表界面
https://list.jd.com/list.html?cat=670%2C671%2C672&go=0
并爬取数据

流程

1. 使用 node 去访问 https://list.jd.com/list.html?cat=670%2C671%2C672&go=0
  => 使用 superagent 第三方包去访问 jd 这个页面
  => 下载: npm i superagent
  => 导入: require()
  => 使用
2. 拿到它的 html 结构
  => 拿到 superagent 的 data.text 就是页面信息
3. 把某些结构里面的内容拿出来组装成一个对象
  => 解析 html 信息, 和组装成一个对象存
  => 使用 cheerio 第三方包
  => 下载: npm i cheerio
  => 导入
  => 使用
4. 存储到数据库里面
  => 使用 mysql 这个包
  => 下载
  => 导入
  => 使用
具体js代码如下
const superagent = require('superagent'
const cheerio = require('cheerio')
const mysql = require('mysql')

const db = mysql.createPool({
  host: '127.0.0.1',
  port: 3306(这里是数据库端口号),
  user: '用户名',
  password: '密码',
 database: '数据库名'
})
const list = []

superagent.get('https://list.jd.com/list.html?cat=670%2C671%2C672&page=3&s=55&click=0', (err, data) => {
if (err) return console.log('爬取页面失败')
 parsePage(data.text)
})

function parsePage(page) {
 const $ = cheerio.load(page)

 $('ul.gl-warp > li').each(function (index, item) {
const obj = {
  goods_img: $(item).find('.p-img a img').prop('src'),
  goods_price: $(item).find('.p-price i').text(),
  goods_title: $(item).find('.p-name em').text(),
  goods_name: $(item).find('.p-name i').text()
}


list.push(obj)
console.log(list)
const sql = 'INSERT INTO `jd_list` VALUES(null, ?, ?, ?, ?)'
const info = [ obj.goods_img, obj.goods_price, obj.goods_title, obj.goods_name ]
db.query(sql, info, (err, data) => {
  if (err) return console.log(err)
})

})
 console.log(list)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

疾风亦有归途ぃ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值