scrapy整合mysql 根据items,创建对应表关系

1.在settings.py文件中添加管道配置:

ITEM_PIPELINES = {
    'jdPrice.pipelines.MySQLSQLAlchemyPipeline': 300
}

2.在pipelines.py中创建MySQLSQLAlchemyPipeline,使用SQLAlchemy库将Item存储到MySQL数据库。(Product 是实体类)

from sqlalchemy.orm import sessionmaker
from jdPrice.models import Product, db_connect, create_table

class MySQLSQLAlchemyPipeline:
    def __init__(self):
        engine = db_connect()
        create_table(engine)
        self.Session = sessionmaker(bind=engine)

    def process_item(self, item, spider):
        session = self.Session()
        product = Product(**item)
        session.add(product)
        session.commit()
        return item

说明: 1.db_connect函数用于创建连接到MySQL的Engine对象2.create_table函数根据已定义的映射类来创建数据表。3.process_item方法中,首先创建了一个Session对象,然后从Item中提取数据构造一个Product对象,并使用session.add将其添加到Session中,最后调用session.commit提交事务。

3.在models.py文件中,定义Product的映射类:

from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Product(Base):
    __tablename__ = 'product'
    id = Column(Integer, primary_key=True)
    title = Column(String(250))
    price = Column(Integer)
def db_connect():
    return create_engine('mysql+pymysql://user:password@localhost/db_name')

def create_table(engine):
    Base.metadata.create_all(engine)

说明:1.Product类中定义了__tablename__属性表示其对应的数据表名,以及三个与数据库中对应列同名的Column对象。2.Base.metadata.create_all(engine)语句会在MySQL数据库中自动为Product类创建一个名为product的表。当Scrapy项目爬取到一个ProductItem时,将自动创建一个名为product的表,并且将Item中的数据存储到该表中。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值