【轉】Python BeautifulSoup 中文亂碼解決方法

這篇文章主要介紹了Python BeautifulSoup中文亂碼問題的2種解決方法,須要的朋友能夠參考下python

解決方法一: 使用python的BeautifulSoup來抓取網頁而後輸出網頁標題,可是輸出的老是亂碼,找了很久找到解決辦法,下面分享給你們 首先是代碼 複製代碼 代碼以下:函數

在剛開始測試的時候發現,雖然輸出是亂碼的,可是寫在文件裏面倒是正常的.而後在網上找了找解決辦法才發現 print一個對象的邏輯:內部是調用對象的__str__獲得對應的字符串的,此處對應的是soup的__str__ 而針對於soup自己,其實已是Unicode編碼,因此能夠經過指定__str__輸出時的編碼爲GBK,以使得此處正確顯示非亂碼的中文 而對於cmd:(中文的系統中)編碼爲GBK,因此只要從新編碼爲gb18030就能夠正常輸出了 就是下面這行代碼 複製代碼 代碼以下: print (soup.title).encode('gb18030')測試

from bs4 import BeautifulSoup
import urllib2

url = 'http://www.jb51.net/'
page = urllib2.urlopen(url)

soup = BeautifulSoup(page,from_encoding="utf8")
print soup.original_encoding
print (soup.title).encode('gb18030')

file = open("title.txt","w")
file.write(str(soup.title))
file.close()

 

for link in soup.find_all('a'):
    print link['href']

解決方法二: BeautifulSoup在解析utf-8編碼的網頁時,若是不指定fromEncoding或者將fromEncoding指定爲utf-8會出現中文亂碼的現象。 解決此問題的方法是將Beautifulsoup構造函數中的fromEncoding參數的值指定爲:gb18030 複製代碼 代碼以下:編碼

import urllib2
from BeautifulSoup import BeautifulSoup

page = urllib2.urlopen('http://www.jb51.net/');
soup = BeautifulSoup(page,fromEncoding="gb18030")
print soup.originalEncoding
print soup.prettify()
相關文章
相關標籤/搜索