初識python之 APP store熱門排行榜 蜘蛛抓取(一)

來源:互聯網
上載者:User

標籤: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()

  運行結果:

            

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.