先看代码
class mysqlPipeline(object):
conn = None
cursor = None
# 连接数据库
def opens_spider(self, spider):
self.conn = pymysql.Connect(host='127.0.0.1', port=3306, user='root', password='123456', db='test',
charset='utf8')
def process_item(self, item, spider):
self.cursor = self.conn.cursor()
try:
self.cursor.execute('insert into qiubai values("%s","%s")' % (item["author"], item["content"]))
self.conn.commit()
except Exception as e:
print(e)
self.conn.rollback() # 回滚
return item
def close_spider(self, spider):
self.cursor.close()
self.conn.close()
这是错误提示
AttributeError: 'NoneType' object has no attribute 'close'
我猜测是使用数据库进行连接是出了问题,但是不知道怎么改,请大佬们看看,谢谢
题主的这一部分代码无助于定位问题。猜测大概是代码某处调用了close_spider方法,而当时的conn或者cursors是None,因此才会抛出'NoneType' object has no attribute 'close'
另外,将conn或者cursors定义为mysqlPipeline类的静态变量,是一个比较罕见的做法。通常,类的静态变量一般用于保存类的静态属性,该属性可被类的方法使用,但不应该被类的方法修改。类名首字母大写,也是约定俗成的规则,模块名则是小写字母开头。
找到出问题的原因了
我把open_spider写成了opens_spider,没想到函数的名称竟然是固定的