今天在学习scrapy的时候,在网上找了一段代码,运行出了一点问题。python
命令行报错:python2.7
name 'reload' is not defined
缘由是,python版本的问题scrapy
原代码以下:ide
import time import sys reload(sys) sys.setdefaultencoding('utf8') class Meiju100Pipeline(object): def process_item(self, item, spider): today = time.strftime('%Y%m%d',time.localtime()) fileName = today + 'movie.txt' with open(fileName,'a') as fp: fp.write(item['storyName'][0].encode("utf8") + '\t' + item['storyState'][0].encode("utf8") + '\t' + item['tvStation'][0] + '\t' + item['updateTime'][0] + '\n') return item
此代码为python2.7版本,学习
reload(sys) #从新加载sys模块 sys.setdefaultencoding('utf8') #设置默认编码格式为utf-8
在3.x版本中,应改为以下:编码
import time import sys import importlib importlib.reload(sys) #sys.setdefaultencoding('utf8') class Meiju100Pipeline(object): def process_item(self, item, spider): today = time.strftime('%Y%m%d',time.localtime()) fileName = today + 'movie.txt' with open(fileName,'a') as fp: fp.write(item['storyName'][0].encode("utf8") + '\t' + item['storyState'][0].encode("utf8") + '\t' + item['tvStation'][0] + '\t' + item['updateTime'][0] + '\n') return item
设置编码格式的代码能够注释掉,由于3.x版本中默认就是utf-8编码。