• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
唯允
博客园    首页    新随笔    联系   管理    订阅  订阅
python---scrapy之MySQL同步存储

假设我们已经能获取到item里定义的字段的数据,接下来就需要保存item的数据到mysql数据库.

pipeline用来存储item中的数据,将爬取到的数据进行二次处理

首先,要做的准备的工作,安装MySQLdb,我安装的是Python-MySQL1.2.5模块.

自定义一个pipeline用mysql来存储item中的数据

class MySQLPipeline(object):
    #自定义一个pipeline用mysql来存储item中的数据
    def __init__(self):
        # 代码连接数据库
        # 1)连接
        # 连接的数据库必须存在
        db = MySQLdb.Connect(host='localhost', user='root', passwd='123456', db='testdb', charset='utf8',use_unicode=True)
        # 游标/指针
        cursor = db.cursor()
        self.db=db
        self.cursor=cursor
        #先删除表

        sql="drop table IF EXISTS test"
        self.cursor.execute(sql)
        self.db.commit()


        sql = "create table if not exists test (id INT PRIMARY KEY auto_increment NOT NULL , title VARCHAR(50) NOT NULL,category_name VARCHAR (100),date_time VARCHAR (20) NOT NULL ,likes INT DEFAULT 0,content longtext ,comment INT DEFAULT 0,collect INT DEFAULT 0,detail_url VARCHAR (255) UNIQUE,src VARCHAR (255))"
        # 参数1:query,填写sql语句
        # 参数2:args,参数,默认是空,填写元组
        self.cursor.execute(sql)
        self.db.commit()

    def process_item(self, item, spider):

        #2)执行相关操作

        # #3)关闭连接,先关cursor,再关db
        # cursor.close()
        # db.close()

        #如果要给所有列添加数据,列名可以不写
        try:
            sql="insert into test (title,category_name, date_time,likes,content, comment,collect, detail_url,src) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)"
            self.cursor.execute(sql, (item['title'],item['category_name'],item['date_time'],item['likes'], item['content'],item['comment'], item['collect'],item['detail_url'],item['src'][0]))
            self.db.commit()
        except:
            print u'数据重复忽略不计'

        return item


    def __del__(self):

        self.cursor.close()
        self.db.close()

process_item(self,item,spider)这个方法会被每个item pipeline组件调用,并且该方法必须返回一个字典数据,item或者抛出一个DropItem异常.

在settings注册下

ITEM_PIPELINES = {

    #MySQL同步写入
    "JobboleSpider.pipelines.MySQLPipeline": 2,


}

 

 

还有可以直接通过模型对象操作数据库的方式称为ORM

特点:不需要写sql语句,可以直接操作数据库

添加:item.save(),

删除:item.delete()

............................

posted on 2017-08-18 21:34  唯允  阅读(296)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3