ошибка при отнесении предметов из скрапа в базу данных - PullRequest
0 голосов
/ 23 мая 2019

я пытаюсь вставить элементы, очищенные скрапом, в базу данных MySQL (создать новую базу данных, если ее раньше не было), я следовал интерактивному учебнику, так как понятия не имею, как это сделать, но ошибка продолжает происходить.

пытаюсь сохранить элемент, содержащий 5 текстовых полей, в базу данных

вот мой конвейер

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html


import mysql.connector


class LinkPipeline(object):

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

    def create_connection(self):
        self.conn = mysql.connector.connect(
            host = 'localhost',
            user = 'root',
            passwd = 'facebook123',
            database = 'link'
        )
        self.curr = self.conn.cursor()

    def create_table(self):
        self.curr.execute("""DROP TABLE IF EXISTS link_tb""")
        self.curr.execute("""create table link_tb(
                        profile text,
                        post_url text,
                        action text,
                        url text,
                        date text
                        )""")

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

    def store_db(self, item):
        self.curr.execute("""insert into link_tb values (%s,%s,%s,%s,%s)""", (
            item['profile'][0],
            item['post_url'][0],
            item['action'][0],
            item['url'][0],
            item['date'][0]
        ))
        self.conn.commit()

вот часть моего паука

        if response.meta['flag'] == 'init':
            #parse root comment
            for root in response.xpath('//div[contains(@id,"root")]/div/div/div[count(@id)!=1 and contains("0123456789", substring(@id,1,1))]'): 
                new = ItemLoader(item=LinkItem(),selector=root)
                new.context['lang'] = self.lang
                new.add_xpath('profile', "substring-before(.//h3/a/@href, concat(substring('&', 1 div contains(.//h3/a/@href, 'profile.php')), substring('?', 1 div not(contains(.//h3/a/@href, 'profile.php')))))")
                new.add_xpath('action','.//div[1]//text()')
                new.add_xpath('date','.//abbr/text()')
                new.add_value('post_url',response.meta['link_url'])
                new.add_value('url',response.url)
                yield new.load_item()

Я ожидаю, что элемент будет храниться в моей базе данных "ссылка", но я продолжаю сталкиваться с этой ошибкой "self.cursor.execute (" "" вставить в значения link_tb (% s,% s,% s,% s,% s)"" ", (AttributeError: у объекта 'LinkPipeline' нет атрибута 'cursor' '

1 Ответ

1 голос
/ 23 мая 2019

Вы определили конструктор как _init_ вместо __init__

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...