Scrapy конвейер mysql ошибка соединительного модуля - PullRequest
0 голосов
/ 11 марта 2020

Я не могу запустить scrapy через мой конвейер до моей локальной базы данных. Я уже установил mysql -connector- python 8.0.19 и могу записывать данные в базу данных в рамках того же проекта, но за пределами конвейера Scrapy. Может кто-нибудь помочь, я не могу понять, почему это не работает.

Когда я пытаюсь отправить данные через конвейер scrapy, я получаю следующую ошибку:

[twisted] CRITICAL: Unhandled error in Deferred:
File "C:\Users\Viking\PycharmProjects\Indigo_Scrp\IndgoScrp\IndgoScrp\pipelines.py", line 7, in <module>
        from mysql.connector import (connection)
        ModuleNotFoundError: No module named 'mysql

Вот мой код для конвейера:

from mysql.connector import (connection)
from mysql.connector import errorcode

class IndgoscrpPipeline(object):

    def __init__(self):
        self.create_connection()
        self.create_table()

    def create_connection(self):
        self.conn = connection.MySQLConnection(
            host='127.0.0.1',
            user='root',
            passwd='',
            database='Python'
        )
        self.curr = self.conn.cursor()

    def open_spider(self, spider):
        print("spider open")

    def process_item(self, item, spider):
        print("Saving item into db ...")
        self.save(dict(item))
        return item

    def close_spider(self, spider):
        self.mysql_close()
##########################################################################

    def mysql_connect(self):
        try:
            return self.curr.connect(**self.conf)
        except self.curr.Error as err:
            if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
                print("Something is wrong with your user name or password")
            elif err.errno == errorcode.ER_BAD_DB_ERROR:
                print("Database does not exist")
            else:
                print(err)
#########################################


    def create_table(self):
        self.curr.execute(""" DROP TABLE IF EXISTS indigo""")
        self.curr.execute(""" Create table indigo(
        Product_Name text,
        Product_Author text,
        Product_Price text,
        Product_Image text
        )""")

    def process_item(self, item, spider):
        self.store_db(item)


    def store_db(self, item):
        self.curr.execute("""Insert Into indigo values (%s,%s,%s,%s)""",
                          (item['Product_Name'][0],
                           item['Product_Author'][0],
                           item['Product_Price'][0],
                           item['Product_Image'][0],
                           )
                          )
        self.conn.commit()


        return item

        self.conn.close()

*

Вот мой код от моего паука

import scrapy


from ..items import IndScrItem
class IndgoSpider(scrapy.Spider):
name = 'Indgo'
start_urls = ['https://www.chapters.indigo.ca/en-ca/books/?link-usage=Header%3A%20books&mc=Book&lu=Main']

def parse(self, response):
    items = IndScrItem()
    Product_Name= response.css('.product-list__product-title-link--grid::text').getall(),
    Product_Author= response.css('.product-list__contributor::text').getall(),
    Product_Price= response.css('.product-list__price--orange::text').getall(),
    Product_Image=  response.css('.product-image--lazy::attr(src)').getall()

    items['Product_Name'] = Product_Name
    items['Product_Author'] = Product_Author
    items['Product_Price'] = Product_Price
    items['Product_Image'] = Product_Image

    yield items

Это строка в файле настроек, которую я должен включить трубопроводы

    ITEM_PIPELINES = {
   'IndgoScrp.pipelines.IndgoscrpPipeline': 100,
}

1 Ответ

0 голосов
/ 15 марта 2020

Я на самом деле обнаружил, что проблема была связана с тем, что ранее pip установил неправильную версию mysql -коннектора, хотя через мой ide pycharm я установил правильный python, был запутан. После удаления обоих и переустановки mysql -connector- python он смог запуститься.

...