开发者社区> 问答> 正文

怎么通过网页内容误别出是否为中文网页?

因定制内容较多,暂时无发现现有爬虫框架满足要求,所以需要自己写(用redis做队列)。我的问题是在爬虫得到一个网页之后,怎么识别出这个网页是否为中文网页?

展开
收起
蛮大人123 2016-03-04 11:43:43 3313 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    首先取响应头里的编码,
    如果是几种中文编码之一,则认为中文网页,
    如果不是中文编码, 也不是几种unicode方案之一, 则不是中文.
    否则再在

    标签里找 charset ,
    如果有并且为几种中文编码之一, 则是中文
    如果不是中文编码, 也不是几种unicode方案之一, 则不是中文.
    否则对body的内容(如果考虑性能问题,可以不对整个body,只对前N个字节)用正则洗标签
    过滤所有ASCII码字符, 剩余部分按字取内码,
    如果考虑性能问题其实取第一个字符就可以了,
    如果性能不重要,可以多采样几个(防止一个页面有中文日文等各种文字混合)
    判断采到的字符的内码是否位于中文unicode区域.
    如果性能非常不重要, 只是要代码简单, 那么做法可以: 正则 1 这样可以取到第一个不是ASCII的字符, 判断这个字符是否是中文字符就可以了
    参考代码:
    #! /usr/bin/env python
    # -*- encoding: utf-8 -*-
    import requests
    import cld2
    
    class Detector(object):
        zh_cn_encodes = ('gbk', 'gb2312', 'gb18030')
        def __init__(self, context):
            self.context = context
    
        def is_zh_cn_encoding(self, ctype):
            ctype = ctype.lower()
            for ec in self.zh_cn_encodes:
                if ec in ctype:
                    return True
            return False
    
        def detect(self):
            assert type(self.context) == type(u''), 'detect unicode string only'
            ret = cld2.detect(self.context.encode('utf-8'))
            return ret[2][0][1] == 'zh'
    
        def url_detect(self):
            r = requests.get(self.context)
            assert r.status_code == 200, 'http code 200 is required'
            ctype = r.encoding
            if ctype and self.is_zh_cn_encoding(ctype):
                return True
            else:
                self.context = r.text
                return self.detect()
    
    if __name__ == '__main__':
        print Detector(u'短中文有bug').detect()
        print Detector(u'网页文件一般没问题').detect()
        print Detector(u'これは日本で').detect()
        url = 'http://segmentfault.com/q/1010000000432652'
        print Detector(url).url_detect()
        url = 'https://code.google.com/p/chromium-compact-language-detector/source/browse/README'
        print Detector(url).url_detect()

    1. x00-xff
    2019-07-17 18:52:03
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载