NodeJs:开始将阿拉伯语放入JSON时将其转换为实体

问题描述 投票:0回答:1

我正在通过抓取网站来构建API,该网站是阿拉伯语的旧网站。

我首先面临一个问题,当我向HTML网站提出请求时,服务器会以一些奇怪的符号返回所有阿拉伯文本!

我已经通过此代码段使用名为iconv-lite的库解决了此问题

// decoding the response to support arabic
responseBody = iconv.decode(Buffer.from(responseBody), "win1256");

现在,如果我返回的HTML效果很好,但是当我开始解析HTML以从中提取数据并将其返回为JSON格式时,问题又回来了,阿拉伯语显示为HTML实体。

响应是这样的!!!! (JSON的每个字段中的文本只有阿拉伯语一个)

"                           بيانات الطالب الأساسية            ( دور مايو )"

如果我Stringify数组,由于某种原因,问题也得到解决! 现在我需要解决此问题,因为我需要数据为JSON格式

所有代码

import { Injectable } from '@nestjs/common';
import { load } from 'cheerio';
import { get } from 'request-promise';
import * as iconv from 'iconv-lite';



@Injectable()
export class FacultyService {
    async getStudentResultsBody(faculty: string = 'Ektsad', seatNumer: string = '240') {
        // search by seatnumber
        let responseBody = await get(`http://xxxx/xxxx/${faculty}/xxx.asp?x_level=2019-2018&xxx=LIKE&xxx=${seatNumer}`, {
            encoding: null,
        });

        // decoding the response to support arabic
        responseBody = iconv.decode(Buffer.from(responseBody), "win1256");

        // parsing the html
        let $ = load(responseBody);

        const stdCode = $('.aspmaker a').attr('href').replace(/[^0-9]/g, "");

        // request to student result page
        let studentResultsPage = await get(`http://xxx/xxx/${faculty}/xx.asp?xxx=${stdCode}`, { encoding: null });

        // decoding the response to support arabic
        studentResultsPage = iconv.decode(Buffer.from(studentResultsPage), "win1256");

        return studentResultsPage;
    }


    async sanatizeData() {
        let body = await this.getStudentResultsBody();

        let $ = load(body);

        let studentDetails: any = $("form > div > table:first-child tr td").map(function (this: any) {
            return $(this).html()
                .trim()
                .split('<br>')
                .map(html => html.replace(/<[^>]*>?/gm, '').trim().split(':'));
        }).get();


        return studentDetails; // getting an issue
    }
}

javascript node.js web-scraping utf-8 cheerio
1个回答
0
投票

您不必关心JSON序列化输出中的实体。 JSON仅用于机器可读。

用户通常不会看到JSON版本。

© www.soinside.com 2019 - 2024. All rights reserved.