今天在学习scrapy的时候,在网上找了一段代码,运行出了一点问题。
命令行报错:
name 'reload' is not defined
原因是,python版本的问题
原代码如下:
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编码。