scrapy使用mysql保存数据示例代码
import pymysql
class MysqlPipeline(object):
"""
同步操作
"""
def __init__(self):
self.conn = pymysql.connect('localhost','root','1234','test')
self.cursor = self.conn.cursor()
def process_item(self,item,spider):
insert_sql = """
insert into test_zxf(name,age,high) VALUES(%s,%s,%s)
"""
self.cursor.execute(insert_sql,(item['name'],item['age'],item['high']))
self.conn.commit()
def close_spider(self,spider):
self.cursor.close()
self.conn.close()
几个注意的点
- 在连接服务器的时候,修改端口需要设置
port=xxxx
- 设置编码
charset='utf8
注意,这里不能使用 utf-8
- 记得一定要使用
conn.commit()
提交数据,否则数据不会保存到数据库
- 代码结束记得关闭游标和连接