2017-05-16 15 views
-1

私は完全にうまく動作するスパイダーを持っていますが、今はアイテムに別の値を追加したいと思います。問題はstampの値がparseにあることです。 stamp値は私がget_detailsに渡すリンクと関連していますが、stampはオリジナルページだけです。生成するたびにstampの値を追加するコードを変更するにはどうすればよいですか?ありがとうカスタム値を渡す治療

def parse(self, response): 
    stamp = response.xpath("//div[@class='byline']/time/@datetime") 

    for url in response.xpath("//h2[@class='post-title']/a/@href").extract(): 
     yield scrapy.Request(url, callback=self.get_details) 

def get_details(self, response): 
     article = ArticleItem() 
     article['title'] = response.xpath("//h1/text()").extract() 
     article['url'] = response.url 
     yield article 
+0

私がわからない場合はIあなたの質問を正しく理解することができますが、コールバックメソッドにデータを渡す必要がある場合は、Scrapy [request.meta](https://doc.scrapy.org/en/1.0/topics/request-response.html#passing-additional)を使用できます。 -data-to-callback-functions)属性を使用します。 – vold

+0

私は '// h2 [@ class = 'post-title']/a/@ href'を使って必要なすべてのリンクを取得し、ページから必要なすべてのデータを取得します。しかし、「スタンプ」はメインページでのみ利用可能です。そして私がつかむ1つのリンクはすべて「切手」です。それが一緒に来るようにアイテムにどのように渡すのですか? – yurashark

+0

あなたは 'parse'でリクエストする' request.meta ['stamp'] = stamp'を追加し、 'get_details'では' stamp = response.meta ['stamp'] 'でスタンプ値を取得できます。 – vold

答えて

1

確かに、ちょうどあなたの要求のメタ属性でスタンプデータを渡した後、あなたのget_details方法で応答オブジェクトから引き出します:

def parse(self, response): 

    # !! As I don't know the actual page these xpaths are my best guesses and need adjustments 
    for item in response.xpath("//li[contains(@class, 'river-block')]"): 
     url = item.xpath(".//h2[@class='post-title']/a/@href").extract()[0] 
     stamp = item.xpath(".//time/@datetime").extract() 
     yield scrapy.Request(url, callback=self.get_details, meta={'stamp': stamp}) 

def get_details(self, response): 
    article = ArticleItem() 
    article['title'] = response.xpath("//h1/text()").extract() 
    article['url'] = response.url 
    article['stamp'] = response.meta['stamp'] 
    yield article 
+0

私はうまくいかなかった。まず、すべてのスタンプを取得してget_detailsに渡します.2番目に、それを保存しません。 – yurashark

+0

スタンプは実際に保存されますが、作成するアイテムごとにすべてのスタンプが各アイテムに保存されます。 – yurashark

+0

これを次のフォーマットで保存します。 ''私はちょうど内部のデータが必要です。 – yurashark