Добавление элементов в 2 таблицы в базе данных MYSQL внутри конвейера с использованием Scrapy - PullRequest
0 голосов
/ 12 апреля 2019

Привет! Я пытаюсь добавить 2 таблицы в свою базу данных MYSQL. Я успешно добавил 2 таблицы, но отдельные элементы, такие как itemA и itemB, не добавляются в базу данных

Если я удаляю itemB, ItemA работает нормально идобавлено в table1, если в 2 таблицах я всегда получал эту ошибку

"NameError: имя 'items_f21' не определено" Любая идея, пожалуйста?

Вот мой код

sales_item_spider.py

    def parse_1(self, response):

    item = GpdealsSpiderItem_hm()

    for product_item_hm in response.css('li.product-item'):

        hm_title = product_item_hm.css('h3.item-heading a.link::text').extract_first()
        hm_regular_price = product_item_hm.css('strong.item-price span.price.regular::text').extract_first()
        hm_sale_price = product_item_hm.css('strong.item-price span.price.sale::text').extract_first()
        hm_photo_url = product_item_hm.css('.image-container img::attr(data-src)').extract_first()
        hm_description_url = product_item_hm.css('h3.item-heading a::attr(href)').extract_first()

        item['hm_title'] = hm_title 
        item['hm_regular_price'] = hm_regular_price 
        item['hm_sale_price'] = hm_sale_price 
        item['hm_photo_url'] = hm_photo_url 
        item['hm_description_url'] = hm_description_url 

        yield item

def parse_2(self, response):

    items_f21 = GpdealsSpiderItem_f21()

    for product_item_forever in response.css('div.pi_container'):

        f21_title = product_item_forever.css('p.p_name::text').extract_first()
        f21_regular_price = product_item_forever.css('span.p_old_price::text').extract_first()
        f21_sale_price = product_item_forever.css('span.p_sale.t_pink::text').extract_first()
        f21_photo_url = product_item_forever.css('img::attr(data-original)').extract_first()
        f21_description_url = product_item_forever.css('a.item_slider.product_link::attr(href)').extract_first()

        items_f21['f21_title'] = f21_title 
        items_f21['f21_regular_price'] = f21_regular_price 
        items_f21['f21_sale_price'] = f21_sale_price 
        items_f21['f21_photo_url'] = f21_photo_url 
        items_f21['f21_description_url'] = f21_description_url 

        yield items_f21

pipelines.py

def create_table(self):
    self.curr.execute("""DROP TABLE IF EXISTS saleitems_hm""")
    self.curr.execute("""create table saleitems_hm(
                    hm_title text,
                    hm_regular_price text,
                    hm_sale_price text,
                    hm_photo_url text,
                    hm_description_url text
                    )""")

    self.curr.execute("""DROP TABLE IF EXISTS saleitems_f21""")
    self.curr.execute("""create table saleitems_f21(
                    f21_title text,
                    f21_regular_price text,
                    f21_sale_price text,
                    f21_photo_url text,
                    f21_description_url text
                    )""")

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

def store_db(self, item):
    self.curr.execute("""insert into saleitems_hm values (%s, %s, %s, %s, %s)""", (
            item['hm_title'],
            item['hm_regular_price'],
            item['hm_sale_price'],
            item['hm_photo_url'],
            item['hm_description_url']
        ))
    self.conn.commit()

    self.curr.execute("""insert into saleitems_f21 values (%s, %s, %s, %s, %s)""", (
            items_f21['f21_title'],
            items_f21['f21_regular_price'],
            items_f21['f21_sale_price'],
            items_f21['f21_photo_url'],
            items_f21['f21_description_url']
        ))
    self.conn.commit()

1 Ответ

0 голосов
/ 14 апреля 2019

Ваш store_db использует переменную items_f21, которая никогда ранее не определялась.

В store_db вы должны использовать только переменную item и использовать соответствующий оператор INSERT в зависимости от типа элемента:

def store_db(self, item):
    if isinstance(item, GpdealsSpiderItem_hm):
        self.curr.execute("""insert into saleitems_hm values (%s, %s, %s, %s, %s)""", (
                item['hm_title'],
                item['hm_regular_price'],
                item['hm_sale_price'],
                item['hm_photo_url'],
                item['hm_description_url']
            ))
    else:
        self.curr.execute("""insert into saleitems_f21 values (%s, %s, %s, %s, %s)""", (
                item['f21_title'],
                item['f21_regular_price'],
                item['f21_sale_price'],
                item['f21_photo_url'],
                item['f21_description_url']
            ))
    self.conn.commit()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...