美文网首页
爬虫&编码

爬虫&编码

作者: 杨小邪yxr | 来源:发表于2018-01-29 15:45 被阅读96次

    写爬虫,尤其时抓取中文页面,总是不可避免的要和不同的编码打交道。
    最常用的UTF-8,GBK,如果抓取时返回的是二进制数据,解码的encoding设置不对很可能引起乱码。

    技巧一:

    我写爬虫常用requests库,可以这样设置

    import requests
    r = requests.get('http://xxx')
    # r.encoding = 'utf-8' 此设置可选
    return r.text
    

    r.text会自动猜测文件编码,返回str格式的内容,但好像经常猜不准,所以还是乱码,很蛋疼。
    所以事先如果知道文件的编码,可以设置r.encoding,告诉他怎么解码。

    技巧二:

    import requests
    r = requests.get('http://xxx')
    # 昨天发现的奇技淫巧
    html_encoding = requests.utils.get_encodings_from_content(r.text)[0]
    return r.content, html_encoding
    

    r.content返回的是二进制的数据,需要显示中文时再r.content.decode(html_encoding)就可以得到正常的中文了。因为requests.utils.get_encodings_from_content(r.text)[0]根据网页正文判断编码,很准,相反,r.encoding只根据文件头部判断,如果一些网页写的不规范,就给你返回ISO-8859

    相关文章

      网友评论

          本文标题:爬虫&编码

          本文链接:https://www.haomeiwen.com/subject/tkzyaxtx.html