BeautifulSoup中文字符编码错误

时间:2016-05-08 17:32:53

标签: python python-2.7 unicode encoding beautifulsoup

我试图识别并保存特定网站上的所有标题,并继续获得我认为编码错误的信息。

该网站是:http://paper.people.com.cn/rmrb/html/2016-05/06/nw.D110000renmrb_20160506_2-01.htm

目前的代码是:

holder = {}  

url = urllib.urlopen('http://paper.people.com.cn/rmrb/html/2016-05/06/nw.D110000renmrb_20160506_2-01.htm').read()

soup = BeautifulSoup(url, 'lxml')

head1 = soup.find_all(['h1','h2','h3'])

print head1

holder["key"] = head1

印刷品的输出是:

[<h3>\u73af\u5883\u6c61\u67d3\u6700\u5c0f\u5316 \u8d44\u6e90\u5229\u7528\u6700\u5927\u5316</h3>, <h1>\u5929\u6d25\u6ee8\u6d77\u65b0\u533a\uff1a\u697c\u5728\u666f\u4e2d \u5382\u5728\u7eff\u4e2d</h1>, <h2></h2>]

我合理地确定那些是unicode字符,但我还没有弄清楚如何说服python将它们显示为字符。

我试图在其他地方找到答案。更明确的问题是这个问题: Python and BeautifulSoup encoding issues

建议添加

soup = BeautifulSoup.BeautifulSoup(content.decode('utf-8','ignore'))

然而,这给了我一个评论中提到的相同错误(&#34; AttributeError:类型对象&#39; BeautifulSoup&#39;没有属性&#39; BeautifulSoup&#39;&#34;) 删除第二个.BeautifulSoup&#39;导致了一个不同的错误(&#34;运行时错误:调用Python对象时超出了最大递归深度&#34;)。

我也试过这里建议的答案: Chinese character encoding error with BeautifulSoup in Python?

通过分解对象的创建

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

但这也产生了递归错误。任何其他提示将非常感激。

谢谢

2 个答案:

答案 0 :(得分:3)

使用unicode-escape解码:

In [6]: from bs4 import BeautifulSoup

In [7]: h = """<h3>\u73af\u5883\u6c61\u67d3\u6700\u5c0f\u5316 \u8d44\u6e90\u5229\u7528\u6700\u5927\u5316</h3>, <h1>\u5929\u6d25\u6ee8\u6d77\u65b0\u533a\uff1a\u697c\u5728\u666f\u4e2d \u5382\u5728\u7eff\u4e2d</h1>, <h2></h2>"""

In [8]: soup = BeautifulSoup(h, 'lxml')

In [9]: print(soup.h3.text.decode("unicode-escape"))
环境污染最小化 资源利用最大化

如果您查看来源,您可以看到数据是 utf-8 编码:

<meta http-equiv="content-language" content="utf-8" />

对于我使用 bs4 4.4.1 只是解码urllib返回的工作正常:

In [1]: from bs4 import BeautifulSoup

In [2]: import urllib

In [3]: url = urllib.urlopen('http://paper.people.com.cn/rmrb/html/2016-05/06/nw.D110000renmrb_20160506_2-01.htm').read()

In [4]: soup = BeautifulSoup(url.decode("utf-8"), 'lxml')

In [5]: print(soup.h3.text)
环境污染最小化 资源利用最大化

当您写入csv时,您需要编码数据 utf-8 str

 .decode("unicode-escape").encode("utf-8")

您可以在dict中保存数据时进行编码。

答案 1 :(得分:0)

这可能会提供一个非常简单的解决方案,但不确定它是否能完全满足你所需的一切,请告诉我:

holder = {}  

url = urllib.urlopen('http://paper.people.com.cn/rmrb/html/2016-05/06/nw.D110000renmrb_20160506_2-01.htm').read()

soup = BeautifulSoup(url, 'lxml')

head1 = soup.find_all(['h1','h2','h3'])

print unicode(head1)

holder["key"] = head1

参考:Python 2.7 Unicode