美体汉字编码

2024-05-15 22:23:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试识别并保存特定站点上的所有标题,并不断获取我认为是编码错误的内容。在

站点是: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

打印输出为:

^{pr2}$

我很确定这些字符是unicode字符,但我还没能找到如何说服python将它们显示为字符的方法。在

我试图在别处找到答案。更明确的问题是: Python and BeautifulSoup encoding issues

建议增加

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

但是,这给了我一个在注释中提到的错误(“AttributeError:type object'BeautifulSoup'没有属性'beauthoulsoup'”) 删除第二个“.BeautifulSoup”会导致另一个错误(“RuntimeError:调用Python对象时超出了最大递归深度”)。在

我也尝试了这里建议的答案: 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)

但这也产生了递归错误。如有其他建议,我们将不胜感激。在

谢谢


Tags: comhttp站点html错误contentcn字符
2条回答

这可能提供了一个相当简单的解决方案,但不确定它是否能完全满足您的需要,请告诉我:

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

使用^{}解码:

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编码的:

^{pr2}$

对于我来说,使用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中保存数据时进行编码

相关问题 更多 >