node实现爬虫功能
程序员文章站
2022-05-30 12:15:50
...
一直想做一个爬虫功能的,但由于种种原因一直搁浅了,最近有时间整理了一下,写了一个简单的爬虫功能,主要用到的模块是cheerio模块,类似于jquery(用法与jquery也很相似),还有request模块
1、新建一个文件夹node
2、在node文件夹下执行下面的操作,DOS操作
- 1)cd node
- 2)npm init (初始化工程)会自动创建一个package.json文件
3、先下载cheerio模块,npm install cheerio --save
4、接着下载request模块npm install request --save
5、由于http模块、fs模块都是内置的包,因此不需要额外添加
6、在node文件夹下
- 1)创建子文件夹datas(用于存放所抓取的新闻文本内容)
- 2)创建子文件夹img(用于存放所抓取的图片资源)
- 3)创建一个app.js文件
话不多说,直接上代码
const http = require('http')
const fs = require('fs')
const cheerio = require('cheerio') // 类似jquery
const request= require('request')
let i = 0
let url = "http://www.scdzzx.net/Item/9888.aspx" // 要抓取的网页地址
function fetchPage(x) {
startRequest(x)
}
function startRequest(x) {
http.get(x, function(res) {
let html = ''
res.setEncoding('utf-8') // 防止中文乱码
res.on('data', function (chunk) {
html += chunk
})
res.on('end', function (){
const $ = cheerio.load(html)
const time = $('.articleCon .property span:first-child').text().trim()
const news_item = {
title: $('.articleCon h2.title').text().trim(),
time,
i: i+1
}
console.log(news_item)
const news_title = $('.articleCon h2.title').text().trim() + '_____' + time
savedContent($, news_title)
savedImg($, news_title)
i = i+1
// 下一篇文章的url
const nextLink = "http://www.scdzzx.net" + $(".others .next a").attr('href');
if (i <= 500) {
fetchPage(nextLink);
}
})
}).on('error',function(err){
console.log('err:', err);
})
}
//该函数的作用:在本地存储所爬取到的新闻内容
function savedContent($, news_title) {
$('#fontzoom p').each(function(index, item){
let x = $(this).text()
// const y = x.substring(0,2).trim()
// console.log(y)
// if (y == '') {
x = x + '\n'
fs.appendFile('./datas/' + news_title + '.txt', x, 'utf-8', function(err){
if (err) {
console.log(err)
}
})
// }
})
}
//该函数的作用:在本地存储所爬取到的图片资源
function savedImg($, news_title) {
$('#fontzoom img').each(function(index, item){
const img_filename = $(this).attr('src').substring($(this).attr('src').lastIndexOf('/')+1)
const img_src = 'http://www.scdzzx.net' + $(this).attr('src')
request.head(img_src, function (err,res,body) {
if (err) {
console.log(err)
}
})
request(img_src).pipe(fs.createWriteStream('./img/' + img_filename))
})
}
fetchPage(url)
最后在DOS下运行代码: node app.js
注意:上面要抓取的网页地址是 http://www.scdzzx.net/Item/9888.aspx 如果要抓取你想要的网址,自行修改地址即可,但要分析的网站结构,比如:代码中提到的
const time = $('.articleCon .property span:first-child').text().trim() // 时间
const news_title = $('.articleCon h2.title').text().trim() // 标题
const nextLink = "http://www.scdzzx.net" + $(".others .next a").attr('href'); // 下一篇文章的url
这是根据抓取的网页的结构去获取的
上一篇: Java实现网页爬虫
下一篇: 实现网页爬虫。