您的位置:首頁技術文章
文章詳情頁

python - 爬蟲獲取網站數據,出現亂碼怎么解決。

瀏覽:92日期:2022-08-04 09:36:09

問題描述

#!/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是內置關鍵字必須更改為其他變量名2、查看網頁源代碼的編碼方式,如果為utf-8在read()后加.decode(’utf-8’),若為其他可以相應解碼

小建議這種小程序寫個函數會比用類來更加方便,無論是使用還是實現

回答2:

推測用的是sublime text?參考這個

回答3:

這兒應該是encode不是decode,而且你的變量名居然是跟內置關鍵字名字一樣

回答4:

應該是encode吧

標簽: Python 編程
国产综合久久一区二区三区