【问题标题】:Scrapy: how to use items in spider and how to send items to pipelines?Scrapy:如何在蜘蛛中使用项目以及如何将项目发送到管道?
【发布时间】:2017-10-10 21:04:34
【问题描述】:

我是scrapy 的新手,我的任务很简单:

对于给定的电子商务网站:

  • 抓取所有网站页面

  • 查找产品页面

  • 如果 URL 指向产品页面

  • 创建项目

  • 处理项目以将其存储在数据库中

我创建了蜘蛛,但产品只是打印在一个简单的文件中。

我的问题是关于项目结构:如何在蜘蛛中使用项目以及如何将项目发送到管道?

我找不到使用项目和管道的项目的简单示例。

【问题讨论】:

    标签: python scrapy scrapy-spider scrapy-pipeline


    【解决方案1】:
    • 如何在我的蜘蛛中使用项目?

    嗯,items 的主要目的是存储你爬取的数据。 scrapy.Items 基本上是字典。要声明您的项目,您必须创建一个类并在其中添加 scrapy.Field

    import scrapy
    
    class Product(scrapy.Item):
        url = scrapy.Field()
        title = scrapy.Field()
    

    您现在可以通过导入您的产品在您的蜘蛛中使用它。

    有关高级信息,我让您查看文档here

    • 如何将项目发送到管道?

    首先,你需要告诉你的蜘蛛使用你的custom pipeline

    settings.py 文件中:

    ITEM_PIPELINES = {
        'myproject.pipelines.CustomPipeline': 300,
    }
    

    您现在可以编写管道并使用您的项目。

    pipeline.py 文件中:

    from scrapy.exceptions import DropItem
    
    class CustomPipeline(object):
        def __init__(self):
            # Create your database connection
    
        def process_item(self, item, spider):
            # Here you can index your item
            return item
    

    最后,在您的spider中,您需要在物品填满后yield

    spider.py 示例:

    import scrapy
    from myspider.items import Product
    
    class MySpider(scrapy.Spider):
        name = "test"
        start_urls = ['http://www.exemple.com']
    
        def parse(self, response):
            doc = Product()
            doc['url'] = response.url
            doc['title'] = response.xpath('//div/p/text()')
            yield doc # Will go to your pipeline
    

    希望对您有所帮助,这是 管道 的文档:Item Pipeline

    【讨论】:

    • 你会在这里放什么? - # Here you can insert your item
    • 在示例中,管道用于将您爬取的数据插入到数据库中。在process_item函数中,您将使用数据库api对数据库中的爬取数据进行索引。所以我到底放在那里取决于我使用的数据库。
    • 感谢您的澄清,您介意插入一个示例吗?
    • 实际上是def __init(self) 而不是def __init__(self)?!?!
    猜你喜欢
    • 2014-09-24
    • 1970-01-01
    • 2013-08-05
    • 2015-06-12
    • 1970-01-01
    • 2012-01-12
    • 2020-07-24
    • 2015-11-13
    • 1970-01-01
    相关资源
    最近更新 更多