1. 程式人生 > >[python爬蟲]對html解析讀取編碼格式,統一轉碼為utf-8

[python爬蟲]對html解析讀取編碼格式,統一轉碼為utf-8

from urllib.request import urlopen
import  chardet
response=urlopen(url,timeout=3)
html_byte=response.read()
chardit1 = chardet.detect(html_byte)
file = open(PROJECT_NAME + '/' + str(ALLNUM) + '.html', 'wb')          html_string=html_byte.decode(chardit1['encoding']).encode('utf-8')
file.write(html_string)
file
.close()

利用到了chardet中的detect方法,獲取chardit1[‘encoding’]探知是何種型別的編碼,對其進行譯碼,再編碼。