繁体   English   中英

Scrapy:如何在蜘蛛中使用项目以及如何将项目发送到管道?

[英]Scrapy: how to use items in spider and how to send items to pipelines?

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

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

  • 抓取所有网站页面

  • 寻找产品页面

  • 如果 URL 指向产品页面

  • 创建一个项目

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

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

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

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

  • 如何使用我的蜘蛛中的物品?

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

import scrapy

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

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

有关高级信息,我让您在此处查看文档

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

首先,您需要告诉您的蜘蛛使用您的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

最后,在你的蜘蛛,你需要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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM