Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

自己编写的脚本获取的中文内容有乱码 #3446

Closed
yetio opened this issue Nov 19, 2019 · 1 comment
Closed

自己编写的脚本获取的中文内容有乱码 #3446

yetio opened this issue Nov 19, 2019 · 1 comment

Comments

@yetio
Copy link

yetio commented Nov 19, 2019

我尝试参考andyt的例子写了一个论坛的脚本,运行时发现中文全部显示为乱码。我试过将编码改成gbk,gb2312,utf-8,均有乱码。请问如何解决?谢谢

const got = require('@/utils/got');
const cheerio = require('cheerio');
const iconv = require('iconv-lite');

const baseUrl = 'https://zzhzbbs.zjol.com.cn/forum.php?mod=guide&view=';
const host = 'https://zzhzbbs.zjol.com.cn/';
const viewProps = {
    newthread: 'newthread',
    hot: 'hot',
    digest: 'disgest',
    new: 'new',
};

module.exports = async (ctx) => {
    const view = ctx.params.view || 'newthread';
    const url = baseUrl + view;
    const response = await got({
        method: 'get',
        url: url,
        responseType: 'arraybuffer'
    });
    // 转码
    const data = iconv.decode(response.data, 'gb2312');
    const $ = cheerio.load(data, { decodeEntities: false } );

    ctx.state.data = {
        title: `${viewProps[view]}`,
        link: url,
        description: `${viewProps[view]}`,
        item: $('.bm_c')
            .find('tbody')
            .map((index, item) => ({
                title:
                    `【` +
                    $(item)
                        .find('td.by a')
                        .eq(0)
                        .text() +
                    `】` +
                    $(item)
                        .find('a.xst')
                        .text(),
                description: '',
                author: $(item)
                    .find('cite')
                    .text()
                    .trim(),
                link:
                    host +
                    $(item)
                        .find('a')
                        .eq(0)
                        .attr('href'),
            }))
            .get(),
    };
};

@hoilc
Copy link
Contributor

hoilc commented Nov 21, 2019

    const response = await got.get(url, {
        responseType: 'buffer',
    });
    const data = iconv.decode(response.data, 'gb2312');
    const $ = cheerio.load(data);

@DIYgod DIYgod closed this as completed Dec 25, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants