一般有三种方式: 第一种:把python默认编码设为你希望的编码,比如我是设为utf-8,直接在python/lib/site-packages新建一个sitecustomize.py文件,然后往里面添加的内容有: #encoding --utf8--- import sys reload(sys) sys.setdefaultencoding('utf8') ------------------------------------------- 但是在Ubuntu系统下应该吧这个文件放到/usr/lib/python2.7/site-packages下,然后重启解释器,如果不知道怎么重启解释器那就重启服务器吧,我没找到怎么重启解释器的方法。 第二种:该更/opt/Python-2.7.7/Lib目录下site.py里面的编码,在def setencoding()方法里面,把 def setencoding(): """Set the string encoding used by the Unicode implementation. The default is 'ascii', but if you're willing to experiment, you can change this.""" encoding = "ascii" # Default value set by _PyUnicode_Init()#这里也行直接设为utf8 if 0:#此处修改为if 1 # Enable to support locale aware default string encodings. import locale loc = locale.getdefaultlocale() if loc[1]: encoding = loc[1] if 0: # Enable to switch off string to Unicode coercion and implicit # Unicode to string conversion. encoding = "undefined" if encoding != "ascii": # On Non-Unicode builds this will raise an AttributeError... sys.setdefaultencoding(encoding) # Needs Python Unicode build ! 第三种:就是直接在你的爬虫脚本里面写上 import sys reload(sys) sys.setdefaultencoding('utf8') 如果这三种方法都没有用,那就可能是你的数据编码有问题,这是你就最好进行排查是数据库的问题还是安装的python有问题,测试方法就是写一个.py脚本往数据库插入值,然后再写一个.py脚本把爬取的数据保存到txt文件中看是否乱码,如果是可以往数据库中插入但是插入是乱编这个时候可以在引入模块上添加以下代码: import os os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8' |
|
来自: yygy321 > 《python scrapy爬虫》