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

far*_*awa 14 python scrapy scrapy-spider scrapy-pipeline

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

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

  • 抓取所有网站页面

  • 寻找产品页面

  • 如果URL指向产品页面

  • 创建一个项目

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

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

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

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

Adr*_*uer 39

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

那么,项目的主要目的是存储您抓取的数据.scrapy.Items基本上都是字典.要声明您的项目,您必须创建一个类并添加scrapy.Field它:

import scrapy

class Product(scrapy.Item):
    url = scrapy.Field()
    title = scrapy.Field()
Run Code Online (Sandbox Code Playgroud)

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

对于高级信息,我让你在这里查看文档

  • 如何将物品发送到管道?

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

settings.py文件中:

ITEM_PIPELINES = {
    'myproject.pipelines.CustomPipeline': 300,
}
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

最后,在你的蜘蛛中,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
Run Code Online (Sandbox Code Playgroud)

希望这会有所帮助,这里是管道的文档:项目管道

  • 在示例中,管道用于将您爬网的数据插入数据库.在`process_item`函数中,您将使用数据库api索引数据库中的已爬网数据.所以我把它放在那里取决于我使用的数据库. (3认同)
  • 你准备好了什么? - `#这里你可以插入你的物品 (2认同)
  • 实际上是`def __init(self)`而不是`def __init__(self)`?!?! (2认同)