近日,正在用python做网页解析,遇到了比较烦人的编码问题,特别时处理中英文结合的网页,编码方案很多的网页时,刚开始很是混乱,就像文章的标题一样。。。
对于字符编码,python推荐在进行数据处理时,使用unicode编码。
多种编码间的使用和转换,其基本思想是:
例如:
我想对各种不同编码的网页解析,并用utf-8编码输出保存。
对于抓取到的网页首先判断是什么编码,这个可以使用一个强大的第三方库chardet 。
import chardet
......
the_page = response.read()
codetype = chardet.detect(the_page)
chardet.detect()
转为unicode编码:
the_page.decode(codetype['encoding'],'ignore')
转为utf-8时,先转为unicode ,再从unicode转为utf-8 :
the_page.decode(codetype['encoding'],'ignore').encode('utf-8','ignore')