栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

好吧,项目的主要目的是存储你爬网的数据。

scrapy.Items
基本上是字典。要声明你的物品,你将必须创建一个类并添加一个类
scrapy.Field

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

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

有关高级信息,我让你在此处检查文档

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

首先,你需要告诉spider使用

custom pipeline

在settings.py文件中:

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

你现在可以编写管道并处理你的项目。

在pipeline.py文件中:

from scrapy.exceptions import DropItemclass 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 scrapyfrom myspider.items import Productclass 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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/380725.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号