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')


总结

这些编码问题其实是一些函数在使用时使用了默认的编码,相应的传入和改变其使用的编码就搞定了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值