zoukankan      html  css  js  c++  java
  • python乱码问题之爬虫篇

    UnicodeDecodeError: 'gbk' codec can't decode byte 0xae in position 167: illegal multibyte sequence

    使用下面的代码有的时候会报错,说什么GBK无法解码...,原因是output的默认编码跟随系统,utf-8的字符GBK有可能不认识于是报错

    from urllib.request import Request
    from urllib.request import urlopen
    
    url = 'http://www.cnblogs.com'
    data = None
    headers = {}
    req = Request(url, data, headers)
    resp = urlopen(req)
    
    print(resp.read().decode('utf-8'))
    

    查看python的默认编码

    import sys
    print(sys.getdefaultencoding()) #utf-8
    

    解决办法

    1. 替换掉不能解析的字符
    2. 设置stdout的编码
    import io  
    import sys  
    import urllib.request  
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf8') #改变标准输出的默认编码  
    res=urllib.request.urlopen('http://www.baidu.com')  
    htmlBytes=res.read()  
    print(htmlBytes.decode('utf-8')) 
    
    1. 永久性修改python默认编码 http://pako.iteye.com/blog/1153343
    import sys
    print(sys.setdefaultencoding()) #utf-8
    

    文件写入编码错误

    print有坑就算了,writelines写入文件也报这个gbk无法编码的问题
    解决办法:

    //设置编码就搞定了
    html=open(line,'w',encoding='utf-8')
    

    ### 总结 这些编码问题其实是一些函数在使用时使用了默认的编码,相应的传入和改变其使用的编码就搞定了。
  • 相关阅读:
    Bootstrap学习笔记
    鼠标画矩形openCV
    开关openCV
    openCV图像形态学
    Android自定义ListView的Item无法响应OnItemClick的解决办法
    0-1背包问题
    java实现矩阵连乘的动态规划
    java 实现排序
    微信小程序--箭头表达式
    微信小程序--navigator url 跳转失效
  • 原文地址:https://www.cnblogs.com/wancy86/p/6844090.html
Copyright © 2011-2022 走看看