87,907
社区成员
发帖
与我相关
我的任务
分享
// 'use strict';
var https = require('https') //Node.js提供了http模块用于搭建HTTP服务端和客户端
var fs = require('fs')
var path = require('path')
var cheerio = require('cheerio')
// var url = 'http://www.xbiquge.la/21/21549/10832214.html' //需要扒的站的网址
var options = { //抓数据请求头,模拟一个浏览器访问
hostname: "www.9zgg.com",
path: '/list-select-id-2-type--area--year--star--state--order-addtime.html',
port: 443,
method:"GET",
headers:{ //可以根据network中页面文件的请求头改写
// 'connection': 'keep-alive',
'sec-fetch-mode': 'navigate',
'user-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36',
'upgrade-Insecure-Requests': '1',
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
'accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8'
}
};
https.get(options,function(res){ //设置请求
res.setEncoding('utf-8')
var html = ''
res.on('data',function(data){
html += data //字符串的拼接
})
res.on('end',function(){ //在页面访问结束后的回调函数
var courseData = filterChapters(html) //用一个数组接受 获取页面数据方法回调的数据
let content = courseData.map((o)=>{ // 将获取到的数据json格式化
return JSON.stringify(o) // JSON.stringify() 方法用于将 JavaScript 值转换为 JSON 字符串。
})
fs.writeFile('./222.json',content, function(err){ //文件路经,写入的内容,回调函数 将json导入到222.json文件
if(err) throw new Error ('写文件失败'+err);
console.log("成功写入文件")
})
})
}).on('error',function(){
console.log('获取资源出错!')
})
function filterChapters(html) {
var $ = cheerio.load(html) // 加载需要的html,然后就可以愉快地使用类似jQuery的语法了
var chapters = $('.col-xs-2') //在html里寻找需要的资源的class
var courseData = [] // 创建一个数组,用来保存资源
chapters.each(function(item, index) { //遍历我们的html文档
var chapter = $(this) //接下来就用jQuery的方法去获取页面中需要抓数据的标签
// console.log(chapter.children('p').find('.continu').text())
var chapterTitle = chapter.children('p').find('img').attr('alt') //标题
var tvUrl = chapter.children('p').find('a').attr('href').split('show/')[1] //跳转链接
var imgUrl = chapter.children('p').find('img').attr('data-original') //图片链接
var updateStatus = chapter.children('p').find('.continu').text() //更新到第几集
var type = '电视剧' //视频类型
var url = `http://www.m4yy.com/show/${tvUrl}` //把跳转链接拼接成完整的URL
courseData.push({
chapterTitle: chapterTitle,
tvUrl: tvUrl,
imgUrl: imgUrl,
updateStatus: updateStatus,
type: type,
url: url
})
})
return courseData //返回需要的资源
}
以前写过这么一个DEMO,返回的数据大概就是
{
"chapterTitle": "只走花路吧",
"tvUrl": "35222.html",
"imgUrl": "https://ae01.alicdn.com/kf/H93a96eef530d40e88b6c053b6568ec67W.png",
"updateStatus": "\t \t更新至109集",
"type": "电视剧",
"url": "http://www.m4yy.com/show/35222.html"
},
{
"chapterTitle": "一个都不能少",
"tvUrl": "36947.html",
"imgUrl": "https://p.ssl.qhimg.com/d/dy_98699842cc2aa1d066b321e543acffcc.jpg",
"updateStatus": "\t \t 更新至23集\n ",
"type": "电视剧",
"url": "http://www.m4yy.com/show/36947.html"
},
这样的JSON