python – BeautifulSoup中文字符编码错误
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – BeautifulSoup中文字符编码错误,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2352字,纯文字阅读大概需要4分钟。
内容图文
![python – BeautifulSoup中文字符编码错误](/upload/InfoBanner/zyjiaocheng/788/05e97b5d2f66453a9401e769c16999a3.jpg)
我正在尝试识别并保存特定网站上的所有标题,并继续得到我认为编码错误.
该网站是: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'))
然而,这给了我同样的错误,在评论中提到(“AttributeError:类型对象’BeautifulSoup’没有属性’BeautifulSoup’”)
删除第二个’.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)
但这也产生了递归错误.任何其他提示将是最受欢迎的.
谢谢
解决方法:
使用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中保存数据时进行编码.
内容总结
以上是互联网集市为您收集整理的python – BeautifulSoup中文字符编码错误全部内容,希望文章能够帮你解决python – BeautifulSoup中文字符编码错误所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。