python抓取并保存html頁面時亂碼問題的解決方法
本文實例講述了python抓取并保存html頁面時亂碼問題的解決方法。分享給大家供大家參考,具體如下:
在用Python抓取html頁面并保存的時候,經(jīng)常出現(xiàn)抓取下來的網(wǎng)頁內(nèi)容是亂碼的問題。出現(xiàn)該問題的原因一方面是自己的代碼中編碼設置有問題,另一方面是在編碼設置正確的情況下,網(wǎng)頁的實際編碼和標示的編碼不符合造成的。html頁面標示的編碼在這里:
這里提供一種簡單的辦法解決:使用chardet判斷網(wǎng)頁的真實編碼,同時從url請求返回的info判斷標示編碼。如果兩種編碼不同,則使用bs模塊擴展為GB18030編碼;如果相同則直接寫入文件(這里設置系統(tǒng)默認編碼為utf-8)。
import urllib2 import sys import bs4 import chardet reload(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 = 'http://chabaoo.cn' download(url)
得到的test.html文件打開如下,可以看到使用的是UTF-8無BOM編碼格式存儲的,也就是我們設置的默認編碼:
更多關于Python相關內(nèi)容感興趣的讀者可查看本站專題:《Python編碼操作技巧總結(jié)》、《Python圖片操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
相關文章
Python圖像處理之直線和曲線的擬合與繪制【curve_fit()應用】
這篇文章主要介紹了Python圖像處理之直線和曲線的擬合與繪制,結(jié)合實例形式分析了Python曲線擬合相關函數(shù)curve_fit()的使用技巧,需要的朋友可以參考下2018-12-12pandas解決數(shù)據(jù)缺失、重復的方法與實踐過程
這篇文章主要介紹了pandas解決數(shù)據(jù)缺失、重復的方法與實踐過程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06