首頁  >  文章  >  後端開發  >  python抓取並儲存html頁面時亂碼問題的

python抓取並儲存html頁面時亂碼問題的

高洛峰
高洛峰原創
2017-03-01 13:25:221569瀏覽

在用Python抓取html頁面並儲存的時候,經常出現抓取下來的網頁內容是亂碼的問題。出現該問題的原因一方面是自己的程式碼中編碼設定有問題,另一方面是在編碼設定正確的情況下,網頁的實際編碼和標示的編碼不符合造成的。 html頁面標示的編碼在這裡:

複製程式碼 程式碼如下:

這裡提供一個簡單的辦法解決:使用chardet判斷網頁的真實編碼,同時從url請求傳回的info判斷標示編碼。如果兩種編碼不同,則使用bs模組擴充為GB18030編碼;如果相同則直接寫入檔案(這裡設定係統預設編碼為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://www.php.cn'
  download(url)

得到的test.html檔案開啟如下,可以看到使用的是UTF-8無BOM編碼格式儲存的,也就是我們設定的默認編碼:

python抓取並儲存html頁面時亂碼問題的

更多python抓取並保存html頁面時亂碼問題的相關文章請關注PHP中文網!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn