2017-06-19 9 views
1

私はScrapingHub APIを使用していて、私のプロジェクトを展開するためにshubを使っています。ただし、アイテムが結果として示されている: - 日付、説明、リンクを公開し、>タイトル残念ながら、私は次の順序でそれを必要とするアイテム出力の順番| Scrap

Example Item Output

。どのように出力をすべてのアイテムクラスについて正確にその順序にすることができますか?

以下

は私のクモの短いサンプルです:

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プログラマーです。

+0

外部リンクを避け、埋め込みコンテンツを好むイメージをお願いします。 –

答えて

1

items.pyに項目を定義する代わりに、collections.OrderedDictを使用できます。ただ、collectionsモジュールをインポートし、parse_node方法では、行変更:あなたが定義された項目をしたい場合、あなたはこのanswerに概説されたアプローチを使用することができ、

item = collections.OrderedDict() 

または:ラインへ

item = {} 

を。あなたの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を参照してください。

+0

items.pyファイルを消去する必要がありますか?または、私は自分のコードに提案したコードを追加することができます – Friezan

+0

答えを編集し、 'items.py'のコードを追加しました。 –

関連する問題