组合模式又叫“部分整体”模式是用小的子对象来构建更大的对象,一组对象的操作必须具有一致性。
    拿爬虫这个案例来举例:我们可以将对文件的操作和对页面爬取到的数据各自封装成一个对象,不仅可以让代码看起来赏心悦目,而且更易于维护
    项目目录:
    简介:实现的代码在src目录中,data 是存储由代码经过处理的数据
    结构如下:
    TypeScript
    |—-src
    |—-crowller.ts
    |—-dellAnalyzer.ts
    |—-data
    |—-node_modules
    |—-package.json

    package.json

    1. {
    2. "name": "TypeScript",
    3. "version": "1.0.0",
    4. "description": "",
    5. "main": "index.js",
    6. "scripts": {
    7. "dev": "ts-node ./src/crowller.ts"
    8. },
    9. "keywords": [],
    10. "author": "",
    11. "license": "ISC",
    12. "devDependencies": {
    13. "@types/superagent": "^4.1.10",
    14. "ts-node": "^9.1.1",
    15. "typescript": "^4.2.4"
    16. },
    17. "dependencies": {
    18. "cheerio": "^1.0.0-rc.6",
    19. "cheerio-select": "^1.4.0",
    20. "css-select": "^4.1.2",
    21. "superagent": "^6.1.0"
    22. }
    23. }

    crowller.ts

    1. import fs from 'fs'
    2. import path from 'path'
    3. import superagent from 'superagent'
    4. import DellAnalyzer from './dellAnalyzer'
    5. export interface Analyzer {
    6. analyze: (html: string, filePath: string) => string
    7. }
    8. class Crowller {
    9. private filePath = path.resolve(__dirname, '../data/course.json')
    10. async getRawHtml() {
    11. const result = await superagent.get(this.url)
    12. return result.text
    13. }
    14. // 写文件
    15. writeFile(content: string) {
    16. fs.writeFileSync(this.filePath, content)
    17. }
    18. async initSpiderProcess() {
    19. const html = await this.getRawHtml()
    20. const fileContent = this.analyzer.analyze(html, this.filePath)
    21. this.writeFile(fileContent)
    22. }
    23. constructor(private url: string, private analyzer: Analyzer) {
    24. this.initSpiderProcess()
    25. }
    26. }
    27. const url = 'http://zblh.gitee.io/hyxc'
    28. const analyzer = new DellAnalyzer()
    29. new Crowller(url, analyzer)

    dellAnalyzer.ts

    1. import fs from 'fs'
    2. import cheerio from 'cheerio'
    3. import { Analyzer } from './crowller'
    4. interface Course {
    5. descs: string
    6. imgSrc: string | undefined
    7. }
    8. interface CourseResult {
    9. time: number
    10. data: Course[]
    11. }
    12. interface Content {
    13. [propName: number]: Course[]
    14. }
    15. export default class dellAnalyzer implements Analyzer {
    16. constructor() {}
    17. private getJsonInfo(html: string) {
    18. const $ = cheerio.load(html)
    19. const courseItems = $('.hide-model .zz-item')
    20. const courseInfos: Course[] = []
    21. courseItems.map((index, element) => {
    22. const descs = $(element).find('p').text()
    23. const imgSrc = $(element).find('img').attr('src')
    24. courseInfos.push({ descs, imgSrc })
    25. })
    26. return {
    27. time: new Date().getTime(),
    28. data: courseInfos
    29. }
    30. }
    31. // 生成需要保存的 JSON
    32. generateJsonContent(courseInfo: CourseResult, filePath: string) {
    33. let fileContent: Content = {}
    34. // 判断文件路径是否存在,如果存在就把里面的内容存给 fileContent
    35. if (fs.existsSync(filePath)) {
    36. fileContent = JSON.parse(fs.readFileSync(filePath, 'utf-8'))
    37. }
    38. fileContent[courseInfo.time] = courseInfo.data
    39. return fileContent
    40. }
    41. public analyze(html: string, filePath: string) {
    42. const courseInfo = this.getJsonInfo(html)
    43. const fileContent = this.generateJsonContent(courseInfo, filePath)
    44. return JSON.stringify(fileContent)
    45. }
    46. }
    47. import fs from 'fs'
    48. import cheerio from 'cheerio'
    49. import { Analyzer } from './crowller'
    50. interface Course {
    51. descs: string
    52. imgSrc: string | undefined
    53. }
    54. interface CourseResult {
    55. time: number
    56. data: Course[]
    57. }
    58. interface Content {
    59. [propName: number]: Course[]
    60. }
    61. export default class dellAnalyzer implements Analyzer {
    62. constructor() {}
    63. private getJsonInfo(html: string) {
    64. const $ = cheerio.load(html)
    65. const courseItems = $('.hide-model .zz-item')
    66. const courseInfos: Course[] = []
    67. courseItems.map((index, element) => {
    68. const descs = $(element).find('p').text()
    69. const imgSrc = $(element).find('img').attr('src')
    70. courseInfos.push({ descs, imgSrc })
    71. })
    72. return {
    73. time: new Date().getTime(),
    74. data: courseInfos
    75. }
    76. }
    77. // 生成需要保存的 JSON
    78. generateJsonContent(courseInfo: CourseResult, filePath: string) {
    79. let fileContent: Content = {}
    80. // 判断文件路径是否存在,如果存在就把里面的内容存给 fileContent
    81. if (fs.existsSync(filePath)) {
    82. fileContent = JSON.parse(fs.readFileSync(filePath, 'utf-8'))
    83. }
    84. fileContent[courseInfo.time] = courseInfo.data
    85. return fileContent
    86. }
    87. public analyze(html: string, filePath: string) {
    88. const courseInfo = this.getJsonInfo(html)
    89. const fileContent = this.generateJsonContent(courseInfo, filePath)
    90. return JSON.stringify(fileContent)
    91. }
    92. }

    如果,想要爬取页面中其余的内容,那么只需改动 dellAnalyzer.ts 文件或者新增一个文件,来进行操作即可。例如想要获取页面所有的内容:
    src目录下新建 allAnalyzer.ts 文件,里面只需写:

    1. import { Analyzer } from './crowller'
    2. export default class dellAnalyzer implements Analyzer {
    3. public analyze(html: string, filePath: string) {
    4. return html
    5. }
    6. }

    crowller.ts 文件,进行简单的修改:

    1. ...
    2. -import DellAnalyzer from './dellAnalyzer'
    3. +import AllAnalyzer from './allAnalyzer'
    4. ...
    5. -const analyzer = new DellAnalyzer()
    6. +const analyzer = new AllAnalyzer()
    7. ...

    最后,运行命令:**$ npm run dev** 即可看到结果