2016-07-19 3 views
0

에서 HTTP 요청을 내가 파이프 라인에서이Scrapy는, 파이프 라인

{ 
    name: "Foo", 
    country: "US", 
    url: "http://..." 
} 

내가 URL에 GET 요청을하고 콘텐츠 _ 및 상태와 같은 일부 헤더를 확인하고 싶은처럼 보이는 스크랩 한 항목이 가정합니다. 헤더가 특정 조건을 충족시키지 못하면 항목을 삭제하려고합니다. 마찬가지로

class MyPipeline(object): 
    def process_item(self, item, spider): 
     request(item['url'], function(response) { 
      if (...) { 
      raise DropItem() 
      } 
      return item 
     }, function(error){ 
      raise DropItem() 
     }) 

파이프 라인을 사용하여 냄새를 맡을 수 없습니다. 어떻게 생각해? 어떤 아이디어가 이것을 달성하는 방법?

거미 :

import scrapy 
import json 

class StationSpider(scrapy.Spider): 
    name = 'station' 
    start_urls = ['http://...'] 

    def parse(self, response): 
     jsonResponse = json.loads(response.body_as_unicode()) 
     for station in jsonResponse: 
      yield station 

답변

2

쉬운 방법

import requests 

def process_item(self, item, spider): 
    response = requests.get(item['url']) 
    if r.status_code ...: 
     raise DropItem() 
    elif response.text ...: 
     raise DropItem() 
    else: 
     return item 

Scrapy 방법

지금은 당신이 파이프 라인 내에서이 작업을 수행하지한다고 생각합니다, 당신은 치료한다 그것은 항목을 굴복하지 않는 거미 내부지만 요청을 누른 다음 yiel 물건을 땡땡이. 우리는 파이프 라인 내부 거미 콜백 동일한 동작을 모방하는

class MyPipeline(object): 

    def __init__(self, crawler): 
     self.crawler = crawler 

    @classmethod 
    def from_crawler(cls, crawler): 
     return cls(crawler) 

    def process_item(self, item, spider): 
     ... 
     self.crawler.engine.crawl(
        Request(
         url='someurl', 
         callback=self.custom_callback, 
        ), 
        spider, 
       ) 

     # you have to drop the item, and send it again after your check 
     raise DropItem() 
    # YES, you can define a method callback inside the same pipeline 
    def custom_callback(self, response): 
     ... 
     yield item 

확인 :

이제 당신은 아직도 당신이 이런 식으로 뭔가를 할 수있는 파이프 라인 내부 scrapy 요청을 포함 할 경우. 추가 요청을하고 싶을 때 항상 항목을 삭제하고 여분의 콜백에 의한 항목을 전달하는 방법을 찾아야합니다.

한 가지 방법은 다른 유형의 항목을 보낼 수 있으며, 파이프 라인의 process_item 내부를 확인할 수 있습니다 :

def process_item(self, item, spider): 
    if isinstance(item, TempItem): 
     ... 
    elif isinstance(item, FinalItem): 
     yield item 
+0

당신이 거미 안에 그것에게 scrapy 방법을 수행하기위한 몇 가지 코드를 보여줄 수 있습니까? 그것은 올바른 해결책 인 것 같습니다. –

+0

거미의 코드를 공유해야합니다 (또는 적어도 나중에 확인하려는 URL로 항목을 생성하는 부분) – eLRuLL