一、亂碼問題描述
經常在爬蟲或者一些操作的時候,經常會出現中文亂碼等問題,如下
原因是源網頁編碼和爬取下來后的編碼格式不一致
二、利用encode與decode解決亂碼問題
字符串在python內部的表示是unicode編碼,在做編碼轉換時,通常需要以unicode作為中間編碼,即先將其他編碼的字符串解碼(decode)成unicode,再從unicode編碼(encode)成另一種編碼。
decode的作用是將其他編碼的字符串轉換成unicode編碼,如str1.decode(‘gb2312'),表示將gb2312編碼的字符串str1轉換成unicode編碼。
encode的作用是將unicode編碼轉換成其他編碼的字符串,如str2.encode(‘utf-8'),表示將unicode編碼的字符串str2轉換成utf-8編碼。
decode中寫的就是想抓取的網頁的編碼,encode即自己想設置的編碼
代碼如下
1
2
3
4
5
6
7
8
9
10
11
12
|
#!/usr/bin/env python # -*- coding:utf-8 -*- # author: xulinjie time:2017/10/22 import urllib2 request = urllib2.request(r 'http://nhxy.zjxu.edu.cn/' ) res = urllib2.urlopen(request).read() res = res.decode( 'gb2312' ).encode( 'utf-8' ) / / 解決亂碼 wfile = open (r './1.html' ,r 'wb' ) wfile.write(res) wfile.close() print res |
或者
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#!/usr/bin/env python # -*- coding:utf-8 -*- # author: xulinjie time:2017/10/22 import urllib2 request = urllib2.request(r 'http://nhxy.zjxu.edu.cn/' ) res = urllib2.urlopen(request).read() res = res.decode( 'gb2312' ) res = res.encode( 'utf-8' ) wfile = open (r './1.html' ,r 'wb' ) wfile.write(res) wfile.close() print res |
但是還要注意:
如果一個字符串已經是unicode了,再進行解碼則將出錯,因此通常要對其編碼方式是否為unicode進行判斷
isinstance(s, unicode)#用來判斷是否為unicode
用非unicode編碼形式的str來encode會報錯
所以最終可靠代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
#!/usr/bin/env python # -*- coding:utf-8 -*- # author: xulinjie time:2017/10/22 import urllib2 request = urllib2.request(r 'http://nhxy.zjxu.edu.cn/' ) res = urllib2.urlopen(request).read() if isinstance (res, unicode ): res = res.encode( 'utf-8' ) else : res = res.decode( 'gb2312' ).encode( 'utf-8' ) wfile = open (r './1.html' ,r 'wb' ) wfile.write(res) wfile.close() print res |
三、如何找到需要抓取的目標網頁的編碼格式
1、查看網頁源代碼
如果源代碼中沒有charset編碼格式顯示可以用下面的方法
2、檢查元素,查看response headers
以上所述是小編給大家介紹的python解決抓取內容亂碼問題(decode和encode解碼)詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:https://blog.csdn.net/w_linux/article/details/78370218