【问题标题】:Sequential Order for Item Output | Scrapy项目输出的顺序 |刮擦
【发布时间】:2017-06-19 18:06:33
【问题描述】:

我正在使用 ScrapingHub API,并且正在使用 shub 来部署我的项目。但是,项目结果如图所示:

不幸的是,我按以下顺序需要它 --> 标题、发布日期、描述、链接。我怎样才能让每个项目类的输出完全按照这个顺序排列?

下面是我的蜘蛛的一个简短示例:

import scrapy

from scrapy.spiders import XMLFeedSpider
from tickers.items import tickersItem
class Spider(XMLFeedSpider):
    name = "Scraper"
    allowed_domains = ["yahoo.com"]
    start_urls = ('https://feeds.finance.yahoo.com/rss/2.0/headline?s=ABIO,ACFN,AEMD,AEZS,AITB,AJX,AU,AKERMN,AUPH,AVL,AXPW
                  'https://feeds.finance.yahoo.com/rss/2.0/headline?s=DRIO
                  'https://feeds.finance.yahoo.com/rss/2.0/headline?s=IDXG,IMMU,IMRN,IMUC,INNV,INVT,IPCI,INPX,JAGX,KDMN,KTOV,LQMT
                  )
    itertag = 'item'

    def parse_node(self, response, node):
        item = {}
        item['Title'] = node.xpath('title/text()',).extract_first()
        item['Description'] = node.xpath('description/text()').extract_first()
        item['Link'] = node.xpath('link/text()').extract_first()
        item['PublishDate'] = node.xpath('pubDate/text()').extract_first()
        return item

另外,这是我附加的 items.py 文件,它与我的蜘蛛的顺序相同,所以我不知道为什么输出不按顺序。

Items.py:

import scrapy

class tickersItem(scrapy.Item):
    Title = scrapy.Field()
    Description = scrapy.Field()
    Link = scrapy.Field()
    PublishDate = scrapy.Field()

我的代码语法是按项目和蜘蛛文件的顺序排列的,我不知道如何修复它。我是一个新的python程序员。

【问题讨论】:

  • 请避免使用外部链接,并希望为您的图片嵌入内容。

标签: scrapy web-crawler scrapinghub


【解决方案1】:

您可以使用collections.OrderedDict,而不是在items.py 中定义项目。只需导入collections 模块并在parse_node 方法中,更改行:

item = {}

到行:

item = collections.OrderedDict()

或者,如果您想要定义的项目,您可以使用answer 中概述的方法。然后您的items.py 将包含以下代码:

from collections import OrderedDict

from scrapy import Field, Item
import six

class OrderedItem(Item):
    def __init__(self, *args, **kwargs):
        self._values = OrderedDict()
        if args or kwargs:  # avoid creating dict for most common case
            for k, v in six.iteritems(dict(*args, **kwargs)):
                self[k] = v

class tickersItem(OrderedItem):
    Title = Field()
    Description = Field()
    Link = Field()
    PublishDate = Field()

您还应该相应地修改您的蜘蛛代码以使用此项目。参考documentation

【讨论】:

  • 我必须清除我的 items.py 文件吗?或者我可以将建议的代码添加到我的代码中
  • 我编辑了答案并添加了items.py的代码。
猜你喜欢
  • 1970-01-01
  • 2020-12-11
  • 1970-01-01
  • 1970-01-01
  • 2016-03-23
  • 2020-01-09
  • 2021-09-06
  • 2014-08-10
  • 1970-01-01
相关资源
最近更新 更多