python - 爬蟲獲取網(wǎng)站數(shù)據(jù),出現(xiàn)亂碼怎么解決。
問題描述
#!/usr/bin/python# -*- coding: utf-8 -*-import urllib2import reimport HTMLParserclass WALLSTREET: def __init__(self, baseUrl):self.url = baseUrl def get_html_content(self):url = self.urlresponse = urllib2.urlopen(url)str = response.read()print strbaseUrl='https://wallstreetcn.com/live/global' #華爾街見文urlws = WALLSTREET(baseUrl)ws.get_html_content()
以上是代碼,寫的很簡單,但是print出來的是亂碼嘗試了 print str.decode(“utf-8“”)但是報錯UnicodeDecodeError: ’utf8’ codec can’t decode byte 0x8b in position 1: invalid start byte
問題解答
回答1:str = response.read()這句有兩個問題:1、str是內(nèi)置關(guān)鍵字必須更改為其他變量名2、查看網(wǎng)頁源代碼的編碼方式,如果為utf-8在read()后加.decode(’utf-8’),若為其他可以相應(yīng)解碼
小建議這種小程序?qū)憘€函數(shù)會比用類來更加方便,無論是使用還是實現(xiàn)
回答2:推測用的是sublime text?參考這個
回答3:這兒應(yīng)該是encode不是decode,而且你的變量名居然是跟內(nèi)置關(guān)鍵字名字一樣
回答4:應(yīng)該是encode吧
