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

### 总结 这些编码问题其实是一些函数在使用时使用了默认的编码,相应的传入和改变其使用的编码就搞定了。
posted @ 2017-05-12 09:47  CooMark  阅读(561)  评论(0编辑  收藏  举报