【发布时间】:2020-06-24 13:23:21
【问题描述】:
我目前正在使用 Scrapy 进行一个小项目,其中我将抓取的数据存储到 MySql 中。问题是我抓取的数据不是1对1的。我在下面提供了MySql的源代码和图像。
问题:向 MySql 发送数据时,只保存每个列表值的第一个值。
main()
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
items()
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 结果
注意 MySql 如何只保存每个列表的第一个值。如果有人可以提供有关如何解决的说明,我将不胜感激。我相信我必须创建 {item_class} 的循环,然后将它们与 {item_type} 匹配,但是我不确定在使用 Scrapy 时如何做到这一点。
【问题讨论】:
-
在store_db函数中,只插入
item的第一个元素 -
@MikhailGenkin 太棒了!我很感激。您对分离数据有什么建议吗?目前整个列表都在 MySql 的一个单元格中。
-
我以为这就是你想要的。您可以通过更改 create_table 函数向表中添加更多列,并将字典解析为这些列
标签: python mysql database web-scraping scrapy