標籤:style blog http color os io strong 檔案
直接上乾貨!!
採用python 2.7.5-windows
開啟 http://www.apple.com/cn/itunes/charts/free-apps/
如可以見採用的是utf-8 編碼
經過一番思想鬥爭 編碼如下 (拍磚別打臉)
#coding=utf-8import urllib2 import urllib import re import thread import time #----------- APP store 熱門排行榜 ----------- class Spider_Model: def __init__(self): self.page = 1 self.pages = [] self.enable = False def GetCon(self): myUrl = "http://www.apple.com/cn/itunes/charts/free-apps/" user_agent = ‘Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)‘ headers = { ‘User-Agent‘ : user_agent } req = urllib2.Request(myUrl, headers = headers) myResponse = urllib2.urlopen(req) myPage = myResponse.read() #encode的作用是將unicode編碼轉換成其他編碼的字串 #decode的作用是將其他編碼的字串轉換成unicode編碼 print myPage print ‘ ‘myModel = Spider_Model()myModel.GetCon()
採集頁面字元集 python檔案字元集統一為utf-8 (貧蛋哥是認為沒啥問題的)
列印輸出結果:
拿出殺手鐧 www.baidu.com
找到原因:
http://blog.csdn.net/lf8289/article/details/2465196
http://www.crifan.com/unicodeencodeerror_gbk_codec_can_not_encode_character_in_position_illegal_multibyte_sequence/
各種狂改中.......
#coding=gbk 編碼修改為gbkimport urllib2 import urllib import re import thread import time #----------- APP store 熱門排行榜 ----------- class Spider_Model: def __init__(self): self.page = 1 self.pages = [] self.enable = False def GetCon(self): myUrl = "http://www.apple.com/cn/itunes/charts/free-apps/" user_agent = ‘Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)‘ headers = { ‘User-Agent‘ : user_agent } req = urllib2.Request(myUrl, headers = headers) myResponse = urllib2.urlopen(req) myPage = myResponse.read() #encode的作用是將unicode編碼轉換成其他編碼的字串 #decode的作用是將其他編碼的字串轉換成unicode編碼 unicodePage = myPage.decode(‘utf-8‘).encode(‘gbk‘,‘ignore‘) #採集頁面編碼為utf-8 轉為 gbk (ignore來忽略非法的字元)
print unicodePage
print ‘ ‘
myModel = Spider_Model()
myModel.GetCon()
運行結果: