python - Python中BeautifulSoup的中文字符编码错误?

标签 python python-2.7 encoding beautifulsoup

我想使用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=) 到底做了什么,但这确实成功了。

关于python - Python中BeautifulSoup的中文字符编码错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32176558/

相关文章:

python - 如何从有序邻接表构建递归字典树

python - 使用 Selenium 下载 google 文档

python - 在Python中,字典理解中的 "if-else and for"是如何工作的

python-2.7 - 使用 ChangeResourceRecordSets Boto3 删除/更新插入时,Change 中缺少字段 'SetIdentifier'

python - 使用 Python 重写 selenium 中 webElement 的 .click() 方法

java - 使用阿拉伯字符创建 zip 文件

mysql - 如何查看存储在 MySQL 列中的原始字节?

python - 在keras中定义自定义损失函数

python - 导入和初始化 GCP googleapis/google-cloud-python 客户端

C# Text.Encoder 和 Text.Encoding 有什么区别