组合模式又叫“部分整体”模式是用小的子对象来构建更大的对象,一组对象的操作必须具有一致性。
拿爬虫这个案例来举例:我们可以将对文件的操作和对页面爬取到的数据各自封装成一个对象,不仅可以让代码看起来赏心悦目,而且更易于维护
项目目录:
简介:实现的代码在src目录中,data 是存储由代码经过处理的数据
结构如下:
TypeScript
|—-src
|—-crowller.ts
|—-dellAnalyzer.ts
|—-data
|—-node_modules
|—-package.json
package.json
{"name": "TypeScript","version": "1.0.0","description": "","main": "index.js","scripts": {"dev": "ts-node ./src/crowller.ts"},"keywords": [],"author": "","license": "ISC","devDependencies": {"@types/superagent": "^4.1.10","ts-node": "^9.1.1","typescript": "^4.2.4"},"dependencies": {"cheerio": "^1.0.0-rc.6","cheerio-select": "^1.4.0","css-select": "^4.1.2","superagent": "^6.1.0"}}
crowller.ts
import fs from 'fs'import path from 'path'import superagent from 'superagent'import DellAnalyzer from './dellAnalyzer'export interface Analyzer {analyze: (html: string, filePath: string) => string}class Crowller {private filePath = path.resolve(__dirname, '../data/course.json')async getRawHtml() {const result = await superagent.get(this.url)return result.text}// 写文件writeFile(content: string) {fs.writeFileSync(this.filePath, content)}async initSpiderProcess() {const html = await this.getRawHtml()const fileContent = this.analyzer.analyze(html, this.filePath)this.writeFile(fileContent)}constructor(private url: string, private analyzer: Analyzer) {this.initSpiderProcess()}}const url = 'http://zblh.gitee.io/hyxc'const analyzer = new DellAnalyzer()new Crowller(url, analyzer)
dellAnalyzer.ts
import fs from 'fs'import cheerio from 'cheerio'import { Analyzer } from './crowller'interface Course {descs: stringimgSrc: string | undefined}interface CourseResult {time: numberdata: Course[]}interface Content {[propName: number]: Course[]}export default class dellAnalyzer implements Analyzer {constructor() {}private 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}}// 生成需要保存的 JSONgenerateJsonContent(courseInfo: CourseResult, filePath: string) {let fileContent: Content = {}// 判断文件路径是否存在,如果存在就把里面的内容存给 fileContentif (fs.existsSync(filePath)) {fileContent = JSON.parse(fs.readFileSync(filePath, 'utf-8'))}fileContent[courseInfo.time] = courseInfo.datareturn fileContent}public analyze(html: string, filePath: string) {const courseInfo = this.getJsonInfo(html)const fileContent = this.generateJsonContent(courseInfo, filePath)return JSON.stringify(fileContent)}}import fs from 'fs'import cheerio from 'cheerio'import { Analyzer } from './crowller'interface Course {descs: stringimgSrc: string | undefined}interface CourseResult {time: numberdata: Course[]}interface Content {[propName: number]: Course[]}export default class dellAnalyzer implements Analyzer {constructor() {}private 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}}// 生成需要保存的 JSONgenerateJsonContent(courseInfo: CourseResult, filePath: string) {let fileContent: Content = {}// 判断文件路径是否存在,如果存在就把里面的内容存给 fileContentif (fs.existsSync(filePath)) {fileContent = JSON.parse(fs.readFileSync(filePath, 'utf-8'))}fileContent[courseInfo.time] = courseInfo.datareturn fileContent}public analyze(html: string, filePath: string) {const courseInfo = this.getJsonInfo(html)const fileContent = this.generateJsonContent(courseInfo, filePath)return JSON.stringify(fileContent)}}
如果,想要爬取页面中其余的内容,那么只需改动 dellAnalyzer.ts 文件或者新增一个文件,来进行操作即可。例如想要获取页面所有的内容:
src目录下新建 allAnalyzer.ts 文件,里面只需写:
import { Analyzer } from './crowller'export default class dellAnalyzer implements Analyzer {public analyze(html: string, filePath: string) {return html}}
crowller.ts 文件,进行简单的修改:
...-import DellAnalyzer from './dellAnalyzer'+import AllAnalyzer from './allAnalyzer'...-const analyzer = new DellAnalyzer()+const analyzer = new AllAnalyzer()...
最后,运行命令:**$ npm run dev** 即可看到结果
