Python抓取gb2312字符集网页中文乱码

来源:互联网 发布:网络公司财务 编辑:程序博客网 时间:2024/05/19 16:27
http://blog.csdn.net/asmcvc/article/details/50790623
最近在学习Python,练习用Python抓取网页内容并解析,在解析gb2312字符集网页时出现中文乱码:
UnicodeEncodeError: 'gbk' codec can't encode character u'\xbb' in position 0: illegal multibyte sequence

网上找了一大推,长篇大论啰嗦了半天都不知道在讲什么,原来Python程序员的表达能力这么差。
后来找到一个解决方案,参考:
http://www.zhetenga.com/view/python%E7%9A%84requests%E7%B1%BB%E6%8A%93%E5%8F%96%E4%B8%AD%E6%96%87%E9%A1%B5%E9%9D%A2%E5%87%BA%E7%8E%B0%E4%B9%B1%E7%A0%81-0abbaa140.html


也就是用网页中的字符编码方式重新编码一次即可:
# 使用requests库封装一个简单的通过get方式获取网页源码的函数
def getsource(url):
html = requests.get(url)
s =
html.text.encode(html.encoding)
# print s
return s
当然 # coding: utf-8 也是要加的。
0 0