I am planning to save images that I have scraped using python scrapy spider directly into my mysql database instead of downloading into local file system. How could I modify my code on pipelines.py to make the downloaded images directly saved to database? Below are some of the codes I have used.
Note: The main problem I have faced is that I am unable to access the image item contents (in binary image file format) using item['images'] as shown in pipelines.py.
items.py
import scrapy
class MyItem(scrapy.Item):
image_urls = scrapy.Field()
images = scrapy.Field()
settings.py
ITEM_PIPELINES = {'scrapy.contrib.pipeline.images.ImagesPipeline': 1}
pipelines.py
import mysql.connector
from decouple import config
class SavetoMySQL:
def __init__(self):
self.user = config("DB_USER")
self.password = config("DB_PASSWORD")
self.host = config("DB_HOST")
self.port = config("DB_PORT")
def connect_database(self):
self.conn = mysql.connector.connect(host=self.host,
user=self.user,
password=self.password,
port=self.port)
def create_table(self):
self.curr = self.conn.cursor()
self.curr.execute("""CREATE TABLE IF NOT EXISTS myitem_db(
image_urls VARCHAR(300),
images LONGBLOB);
""")
def store_db(self, item):
insert_stmt = ("""INSERT INTO Book(image_urls, images)
VALUES (%s,%s)""")
data = (item['image_urls'],item['images']) # item["images"] cannot access and save image binary file format into database
self.curr.execute(insert_stmt, data)
def open_spider(self, spider):
self.connect_database()
self.create_table()
def process_item(self, item, spider):
self.store_db(item)
return item
def close_spider(self, spider):
self.curr.close()
self.conn.close()