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中的数据存储到该表中。