# 建立数据库 create database item_database; set global validate_password_length = 1; set global validate_password_policy = 0; grant all on item_database.* to 'xkd'@'%' identified by '123456'; flush privileges; # 根据item建立数据表 create table item (title varchar(255) not null, image_url varchar(255) not null, date date not null, image_path varchar(255) not null, url varchar(255) not null, url_id char(50) not null primary key);
pip install mysqlclient
ITEM_PIPELINES = { # 'XKD_Dribbble_Spider.pipelines.XkdDribbbleSpiderPipeline': 300, # 当items.py模块yield以后,默认就是下载image_url的页面 'XKD_Dribbble_Spider.pipelines.ImagePipeline': 1, 'XKD_Dribbble_Spider.pipelines.MysqlPipeline': 2, }
process_item()
方法将item的字段读取出来,再提交到数据中表中; 最后运行项目成功后,能够使用命令行工具查看数据是否插入成功;class MysqlPipeline: def __init__(self): self.conn = MySQLdb.connect(host='localhost', user='xkd', password='123456', database='item_database', use_unicode=True, charset='utf8') self.cursor = self.conn.cursor() def process_item(self, item, spider): sql = 'insert into item(title, image_url, date, image_path, url, url_id)' \ 'values (%s, %s, %s, %s, %s, %s)' date = item['date'] self.cursor.execute(sql, args=(item['title'], item['image_url'], date.strftime('%y-%m-%d'), item['image_path'], item['url'], item['url_id'])) self.conn.commit() return item def spider_closed(self, spider): self.cursor.close() self.conn.close()
先建立数据库:create database 数据库名;
html
而后给用户受权:grant all on 数据库名.* to '用户名'@'%' identified by '密码';
mysql
记得刷新MySQL的系统权限相关表:flush privileges;
sql
在进入建立好的数据库根据item建立数据库表:create table item(字段);
数据库
首先登陆MySQL数据库,命令行:mysql -u用户名 -p密码;
ide
而后选择咱们建立的数据库,命令行:use 数据库名;
工具
而后就能够查看数据库表是否成功插入数据,命令行:select * from item;
;url
当数据库表中数据不少的时候,咱们能够在查询语句末尾加入一个\G
参数,横向的表结构会转为使用纵向表结构输出,利于阅读;命令行
参考:https://www.9xkd.com/user/plan-view.html?id=1693196261code