Skip to main content
 首页 » 编程设计

python之Python 中 BeautifulSoup 的汉字编码错误

2024年10月24日14lovecherry

我想用BeatifulSoup从网站上获取表格中的数据,但是无法正确抓取汉字。 这是我的代码:

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
import urllib2 
from bs4 import BeautifulSoup 
html=urllib2.urlopen("http://www.515fa.com/che_1978.html").read() 
soup=BeautifulSoup(html,from_encoding="UTF-8") 
print soup.prettify() 

而汉字是这样显示的:

<td align="center" bgcolor="#FFFFFF" u1:str="" width="173"> 
               ćé¸</td> 
<td align="center" bgcolor="#FFFFFF" u1:str="" width="149"> 
               ä¸ćľˇĺ¤§äź</td> 
<td align="center" bgcolor="#FFFFFF" u1:str="" width="126"> 
               大äź</td> 

我真的不知道“ä¸ćľˇĺ¤§äź”是什么。我尝试将编码“utf-8”更改为“gb18030”,但没有用。 我怎样才能得到正确的汉字?谢谢!

请您参考如下方法:

尝试:

html = urllib2.urlopen("http://www.515fa.com/che_1978.html") 
content = html.read().decode('utf-8', 'ignore') 
soup = BeautifulSoup(content) 

不确定 BeautifulSoup(from_encoding=) 到底做了什么,但这确实成功了。