Python爬取中文页面的时候出现的乱码问题(续)
2016-03-10 17:32
519 查看
我在上一篇博客中说明了在爬取数据的时候,把数据写入到文件的乱码问题
在这一篇里面我做一个总结:
1、首先应该看一个案例
我把数据写在.py文件中:
#coding:utf-8
s = 'hehe测试中文字符'
ss = u'hehe测试中文字符'
uu = s.decode('utf-8')
print s #输出乱码
print uu #正常
print ss #正常
这里需要对中文数据进行编码,输出正常
2、我们针对爬取回来的数据
在读取页面数据的时候已经对其编码 response.read().decode('utf-8')
在把数据写入到数据库的时候,只需要把数据库的连接指定为 utf-8 就可以
MySQLdb.Connect(host=v_host,port=int(v_port),user=v_user,passwd=v_passwd,db=v_db,charset='utf8')
3、可以直接把读取来的数据直接写入到数据库中,不会出现乱码
py文件的其他地方不需要在进行其他的编码,仅仅是在读取response里面的数据的时候进行编码一次
4、在设置Mysql编码的时候切记是:utf8,中间没有横杠
不然会报错:_mysql_exceptions.OperationalError: (2019, “Can’t initialize character set utf-8
在这一篇里面我做一个总结:
1、首先应该看一个案例
我把数据写在.py文件中:
#coding:utf-8
s = 'hehe测试中文字符'
ss = u'hehe测试中文字符'
uu = s.decode('utf-8')
print s #输出乱码
print uu #正常
print ss #正常
这里需要对中文数据进行编码,输出正常
2、我们针对爬取回来的数据
在读取页面数据的时候已经对其编码 response.read().decode('utf-8')
在把数据写入到数据库的时候,只需要把数据库的连接指定为 utf-8 就可以
MySQLdb.Connect(host=v_host,port=int(v_port),user=v_user,passwd=v_passwd,db=v_db,charset='utf8')
3、可以直接把读取来的数据直接写入到数据库中,不会出现乱码
py文件的其他地方不需要在进行其他的编码,仅仅是在读取response里面的数据的时候进行编码一次
4、在设置Mysql编码的时候切记是:utf8,中间没有横杠
不然会报错:_mysql_exceptions.OperationalError: (2019, “Can’t initialize character set utf-8
相关文章推荐
- [Leetcode]@python 110. Balanced Binary Tree
- 深入理解Lambda
- [Leetcode]@python 109. Convert Sorted List to Binary Search Tree
- [Leetcode]@python 108. Convert Sorted Array to Binary Search Tree
- 整理-python好问题
- python 3.3 安装paramiko模块
- 谈谈python中的遍历
- [Leetcode]@python 107. Binary Tree Level Order Traversal II
- [Leetcode]@python 106. Construct Binary Tree from Inorder and Postorder Traversal
- python代码格式检查工具部署pre_commit
- Python讀寫Excel文件的實例
- numpy.hstack(tup)
- numpy.random.uniform(记住文档网址)
- Windows下Python的Django框架环境部署及应用编写入门
- Python格式化日期时间的函数
- ascii' codec can't encode characters in position 598-599: ordinal not in range(128)解决方案
- python读写excel
- Python实例讲解 -- 获取本地时间日期(日期计算)
- java + spring (jython\python\script) Error:SyntaxError: no viable alternative at character '\n'
- Java调用Python返回乱码问题解决