【问题标题】:Scrapy + PostgreSQL - Automatic Items and Pipeline for Custom ETL (Truncate > Insert > Upsert > Delete)Scrapy + PostgreSQL - 自定义 ETL 的自动项目和管道(截断>插入>更新插入>删除)
【发布时间】:2020-01-06 01:13:16
【问题描述】:

我已经有一些工作蜘蛛和代码来实现我想要的,但我正在寻找有关如何为我正在从事的项目更有效地整合事物的建议。

我目前的流程涉及:

  • 在 Scrapy 中:使用 scrapy.Item 手动创建项目
  • 在 Scrapy 中:抓取,将每个 Item 行输出到 JSON Lines (JL) 文件

    • 当前管道:
    #pipelines.py
    class MyPipeline(object):
        def process_item(self, item, spider):
            for field in item.fields:
                item.setdefault(field, None)
            return item
    
  • 使用 SQL Alchemy 的外部 Scrapy:truncate incoming tablebulk insert 使用 Pandas to_sql 的 JL 文件

  • 使用 SQL Alchemy 的外部 Scrapy:update incoming table row_uuid column(所有相关列的 md5 哈希)
  • 使用 SQL Alchemy 的外部 Scrapy:将传入数据表插入 (insert...on conflict...where row_uuid is distinct from) 到源数据表中
  • 外部 Scrapy w/SQL Alchemy:delete 必要时来自源表(404 错误等)

理想情况下,我想使用适当的管道在 Scrapy 中执行所有这些操作。我见过提到datasetopen_spiderprocess_itemclose_spider 的组合会有帮助吗?我有一些问题:

  • 是否可以直接从现有数据库表中填充/定义 Scrapy Items 而无需手动列出列?
  • 如果 Spider 中有多个方法(parse、parse_detail 等),每个方法都有自己的 Item,Pipeline 是否能够插入到正确的数据库表中?
  • 是否可以一次批量插入 X 项,而不是一次插入一项?
  • 以下是一种潜在的方法吗?我认为需要进行其他更改...

    #pipelines.py
    class SqlPipeline(object):
        def __init__(self, db_conn):
            #Connect to DB here?
    
        def open_spider(self, spider):
            #Truncate specific incoming table here?
    
        def process_item(self, item, spider):
            #(Bulk) insert item row(s) into specific incoming table?
            #Where would you define the table for this?
    
        def close_spider(self, spider):
            #Update row_uuid for specific incoming table?
            #Do upsert and delete rows for specific source table?
            #Close DB connection here?
    

    感谢您的帮助!

【问题讨论】:

    标签: python web-scraping sqlalchemy scrapy


    【解决方案1】:

    Scrapy 中的管道用于执行您所说的操作。 回答您的问题:

    • 是否可以直接从现有数据库表中填充/定义 Scrapy Items 而无需手动列出列?

    我不明白“手动收听列”。我猜你在数据库中有一个包含一堆列的表。这些列必须在您的项目中定义,因为它们将映射到数据库。如果不是,您希望如何将每个字段映射到表中的列?

    • 如果 Spider 中有多个方法(parse、parse_detail 等),每个方法都有自己的 Item,管道是否能够插入到正确的数据库表中?

    是的。您可以定义多个管道(及其权重),以便将每个项目的不同进程分开并正确分开。

    • 是否可以一次批量插入 X 项,而不是一次插入一项? 以下是一种潜在的方法吗?

    是的。当然!您必须将其定义到您的管道中。每个人的逻辑可能不同!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-08
      • 2018-02-10
      • 2011-04-07
      • 1970-01-01
      • 2015-03-27
      • 2015-05-17
      相关资源
      最近更新 更多