zoukankan      html  css  js  c++  java
  • pythonscrapy之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()

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

  • 相关阅读:
    读书笔记五
    读书笔记四
    读书笔记3(Teamwork)
    读书笔记二(合格的软件工程师)
    读书笔记1(软件 = 程序 + 工程)
    关于使用Java开发Mis系统
    课堂动手动脑
    Quartz学习
    把数据库中取出的DataTable转换成一个对象 或者对象列表
    SAE上使用cron定时发微博
  • 原文地址:https://www.cnblogs.com/kidl/p/7392322.html
Copyright © 2011-2022 走看看