博文配套视频课程:24小时实现从零到AI人工智能
创建数据库的表结构
-- auto-generated definition
drop database if exists jianshu;
create database jianshu default character set utf8;
use jianshu;
drop table if exists article;
create table article
(
id int not null auto_increment,
title varchar(20),
name varchar(20),
url longtext,
collection longtext,
primary key (id)
);
select * from article
实现数据插入功能
首先要在setting.py框架中启用 ITEM_PIPELINES,否则pipelines.py类里面的process_item方法是不会执行的。如果后续想创建连接池提高性能则搜索:adbapi解决方案
import pymysql
class JianshuPipeline(object):
def __init__(self):
dbparam = {
'host': '127.0.0.1',
'port': 3306,
'user': 'root',
'password': 'root',
'database': 'jianshu',
'charset': 'utf8'
}
# 查看源码,看需要哪些参数
self.conn = pymysql.connect(**dbparam)
# 创建一个游标
self.cursor = self.conn.cursor()
def process_item(self, item, spider):
sql = "insert into article(title,name,collection,url) values (%s,%s,%s,%s)"
self.cursor.execute(sql, (item['title'], item['name'],item['collection'], item['url']))
self.conn.commit()
return item