对代码进行优化,处理耦合
import superagent from 'superagent'import cheerio from 'cheerio'interface Course {descs: stringimgSrc: string | undefined}class Crowller {private url = 'http://zblh.gitee.io/hyxc'getJsonInfo(html: string) {const $ = cheerio.load(html)const courseItems = $('.hide-model .zz-item')const courseInfos: Course[] = []courseItems.map((index, element) => {const descs = $(element).find('p').text()const imgSrc = $(element).find('img').attr('src')courseInfos.push({ descs, imgSrc })})return {time: new Date().getTime(),data: courseInfos}}async getRawHtml() {const result = await superagent.get(this.url)return result.text}async initSpiderProcess() {const html = await this.getRawHtml()const courseResult = this.getJsonInfo(html)console.log(courseResult)}constructor() {this.initSpiderProcess()}}const crowller = new Crowller()
将数据进行JSON的存储,添加generateJsonContent 方法
// ts -> d.ts 翻译文件 -> jsimport fs from 'fs'import path from 'path'import superagent from 'superagent'import cheerio from 'cheerio'interface Course {descs: stringimgSrc: string | undefined}interface CourseResult {time: numberdata: Course[]}interface Content {[propName: number]: Course[]}class Crowller {private url = 'http://zblh.gitee.io/hyxc'getJsonInfo(html: string) {const $ = cheerio.load(html)const courseItems = $('.hide-model .zz-item')const courseInfos: Course[] = []courseItems.map((index, element) => {const descs = $(element).find('p').text()const imgSrc = $(element).find('img').attr('src')courseInfos.push({ descs, imgSrc })})return {time: new Date().getTime(),data: courseInfos}}async getRawHtml() {const result = await superagent.get(this.url)return result.text}// 生成需要保存的 JSONgenerateJsonContent(courseInfo: CourseResult) {const filePath = path.resolve(__dirname, '../data/course.json')let fileContent: Content = {}// 判断文件路径是否存在,如果存在就把里面的内容存给 fileContentif (fs.existsSync(filePath)) {fileContent = JSON.parse(fs.readFileSync(filePath, 'utf-8'))}fileContent[courseInfo.time] = courseInfo.datareturn fileContent}async initSpiderProcess() {const filePath = path.resolve(__dirname, '../data/course.json')const html = await this.getRawHtml()const courseInfo = this.getJsonInfo(html)const fileContent = this.generateJsonContent(courseInfo)fs.writeFileSync(filePath, JSON.stringify(fileContent))}constructor() {this.initSpiderProcess()}}const crowller = new Crowller()
