如何解決用 Beautiful Soup 抓取網頁卻得到亂碼的問題?
def scoreScanner(username,password):
a_jar = cookielib.CookieJar() b_jar = urllib2.build_opener(urllib2.HTTPCookieProcessor(a_jar))urllib2.install_opener(b_jar)
dust1 = http://xxx dust2 = username dust3 = mm=dust4 = password
dust5 = yhlbdm=01 response = urllib2.urlopen(dust1 dust2 dust3 dust4 dust5) next = urllib2.urlopen("http://xxxx/xxx") doc = next.read()soup = BeautifulSoup(.join(doc))
soup.originalEncoding soup =str(soup) score_raw = str(soup) #print score_raw#print zzz
saveFile(username,score_raw)
可能編碼識別錯了,建議創建soup對象時手動把正確的編碼傳過去,國內的網站編碼主要是gb2312和utf8,對於大部分非utf8編碼中文網站可以用gb18030通吃 &> &> &> encoding = "gb18030"
&> &> &> soup = BeautifulSoup(page, fromEncoding=encoding)
這個問題我之前也遇到了,後來在StackOverflow上提問,找到了解決方法。
樓上所說的編碼問題只是一個方面,使用GB18030確實能夠解決。另一個造成亂碼的原因是壓縮格式。很多規模較大的網站都是以gzip的壓縮格式輸出頁面的,所以在用BS解析之前需要先判斷該網頁是否經過壓縮,如果經過壓縮則先進行解壓操作。完整代碼如下:#-*- coding: utf-8 -*-
from __future__ import print_function
import gzip
import StringIO
import urllib2
from BeautifulSoup import BeautifulSoup
url = http://iccna.blog.sohu.com/164572951.html
response = urllib2.urlopen(url)
data = response.read()
data = StringIO.StringIO(data)
gzipper = gzip.GzipFile(fileobj=data)
html = gzipper.read()
soup = BeautifulSoup(html, fromEncoding=gb18030)
print(soup)
一般都是編碼的問題,這個問題很吐血。
以前搞這塊的時候,總算是找到了一個學習英文的充分理由,就是英文編碼一般不容易出問題。你確定是BeautifulSoup的問題?不是urllib2的使用問題?我一般都用requests。如果你是response.text,那麼你指定的encoding可能不對。我一般直接用response.content(binary形式)。
response = requests.get(url)
bs = BeautifulSoup(response.content, "lxml")
對要輸出的數據使用unicode函數試試看,比如要輸出title,就輸出unicode(title)
裝個chardet,beautifulsoup 如果無法判斷頁面編碼會通過這個再嘗試一次
我的解決方案是用原來的網頁編碼encode輸出。
例子:
soup = BeautifulSoup(html, "html.parser")
print (soup.title).encode(soup.original_encoding)
列印的時候指定gb18030編碼即可:
print soup.encode(gb18030)
推薦閱讀: