本文實例講述了python抓取并保存html頁面時亂碼問題的解決方法。分享給大家供大家參考,具體如下:
在用Python抓取html頁面并保存的時候,經常出現抓取下來的網頁內容是亂碼的問題。出現該問題的原因一方面是自己的代碼中編碼設置有問題,另一方面是在編碼設置正確的情況下,網頁的實際編碼和標示的編碼不符合造成的。html頁面標示的編碼在這里:
這里提供一種簡單的辦法解決:使用chardet判斷網頁的真實編碼,同時從url請求返回的info判斷標示編碼。如果兩種編碼不同,則使用bs模塊擴展為GB18030編碼;如果相同則直接寫入文件(這里設置系統默認編碼為utf-8)。
import urllib2import sysimport bs4import chardetreload(sys)sys.setdefaultencoding('utf-8')def download(url): htmlfile = open('test.html','w') try: result = urllib2.urlopen(url) content = result.read() info = result.info() result.close() except Exception,e: print 'download error!!!' print e else: if content != None: charset1 = (chardet.detect(content))['encoding'] #real encoding type charset2 = info.getparam('charset') #declared encoding type print charset1,' ', charset2 # case1: charset is not None. if charset1 != None and charset2 != None and charset1.lower() != charset2.lower(): newcont = bs4.BeautifulSoup(content, from_encoding='GB18030') #coding: GB18030 for cont in newcont: htmlfile.write('%s/n'%cont) # case2: either charset is None, or charset is the same. else: #print sys.getdefaultencoding() htmlfile.write(content) #default coding: utf-8 htmlfile.close()if __name__ == "__main__": url = '//m.survivalescaperooms.com' download(url)得到的test.html文件打開如下,可以看到使用的是UTF-8無BOM編碼格式存儲的,也就是我們設置的默認編碼:

更多關于Python相關內容感興趣的讀者可查看本站專題:《Python編碼操作技巧總結》、《Python圖片操作技巧總結》、《Python數據結構與算法教程》、《Python Socket編程技巧總結》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答
圖片精選