提问者:小点点

Scrapy和MySQL:存储列表


我目前正在与Scrapy一起做一个小项目,在这个项目中,我将收集到的数据存储到MySQL中。 问题是我收集的数据不是1比1。 我在下面提供了MySql的源代码和图像。

问题:将数据发送到MySql时,只保存每个列表值的第一个值。

import scrapy

from ..items import CsgoProjectItem

item = CsgoProjectItem()

class ListOfSkins(scrapy.Spider):
    name = "list_of_skins"
    start_urls = ['https://csgostash.com/']

def parse(self, response):

    main_li_dropdown = response.css('li.dropdown')

    for item_category in main_li_dropdown[:-1]:
        item_class = item_category.css('.dropdown-toggle::text').getall() # Get Class (Step 1/4)

        item['item_class'] = item_class

        if item_category.css('.dropdown-menu.navbar-dropdown-large a::text'):
            item_type = item_category.css('.dropdown-menu.navbar-dropdown-large a::text').getall() # Get Type (Step 2/4 a)

            item['item_type'] = item_type

        if item_category.css('.dropdown-menu.navbar-dropdown-small a::text'):
            item_type = item_category.css('.dropdown-menu.navbar-dropdown-small a::text').getall() # Get Type (Step 2/4 b)

            item['item_type'] = item_type

        yield item
import scrapy

class CsgoProjectItem(scrapy.Item):
    item_class = scrapy.Field()
    item_type = scrapy.Field()
import mysql.connector
import os

class CsgoProjectPipeline:

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

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

    def create_table(self):
        self.curr.execute("""DROP TABLE IF EXISTS item_list""")
        self.curr.execute("""CREATE TABLE item_list(
        class text,
        type text
        )""")

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

    def store_db(self, item):
        self.curr.execute("""INSERT INTO item_list VALUES (%s,%s)""", (
            item['item_class'][0],
            item['item_type'][0]
        ))
        self.conn.commit()

注意MySql是如何只保存每个列表的第一个值的。 如果有人能提供如何解决的指导,我将不胜感激。 我认为我必须创建一个{item_class}的循环,然后将它们与{item_type}相匹配,但是我不确定在使用Scrapy时如何做到这一点。


共1个答案

匿名用户

store_db函数中,只插入item的第一个元素:

self.curr.execute("""INSERT INTO item_list VALUES (%s,%s)""", (
        item['item_class'][0],
        item['item_type'][0]
    ))

您需要插入完整列表。 你需要把整本词典都倒进去。 试试看

self.curr.execute("""INSERT INTO item_list VALUES (%s,%s)""", (
        item['item_class'][0],
        json.dumps(item['item_type'])
    ))

不要忘记安装和导入json包,它可以将字典转换成字符串。