0
치료를 테스트 할 코드가 있습니다. 내 목표는 단말기에서 scrapy
명령을 호출하지 않고도 치료를 사용하는 것이므로이 코드를 다른 위치에 삽입 할 수 있습니다.할당 된 파이프 라인을 호출하지 않는 치료
코드는 다음과 같다 :
보시다시피from scrapy import Spider
from scrapy.selector import Selector
from scrapy.item import Item, Field
from scrapy.crawler import CrawlerProcess
import json
class JsonWriterPipeline(object):
file = None
def open_spider(self, spider):
self.file = open('items.json', 'wb')
def close_spider(self, spider):
self.file.close()
def process_item(self, item, spider):
line = json.dumps(dict(item)) + "\n"
self.file.write(line)
return item
class StackItem(Item):
title = Field()
url = Field()
class StackSpider(Spider):
name = "stack"
allowed_domains = ["stackoverflow.com"]
start_urls = ["http://stackoverflow.com/questions?pagesize=50&sort=newest"]
def parse(self, response):
questions = Selector(response).xpath('//div[@class="summary"]/h3')
for question in questions:
item = StackItem()
item['title'] = question.xpath('a[@class="question-hyperlink"]/text()').extract()[0]
item['url'] = question.xpath('a[@class="question-hyperlink"]/@href').extract()[0]
yield item
if __name__ == '__main__':
settings = dict()
settings['USER_AGENT'] = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'
settings['ITEM_PIPELINES'] = {'JsonWriterPipeline': 1}
process = CrawlerProcess(settings=settings)
spider = StackSpider()
process.crawl(spider)
process.start()
, 코드 자체에 포함 나는 두 가지 설정이 우선이다 USER_AGENT 및 ITEM_PIPELINES. 그러나 JsonWriterPipeline
클래스의 디버그 지점을 설정하면 코드가 실행되고 디버그 지점에 도달하지 못하므로 사용자 지정 파이프 라인이 사용되지 않습니다.
어떻게이 문제를 해결할 수 있습니까?
실제로 '{'__main __. JsonWriterPipeline ': 1}'이 문제 였고 두 번째 오류는 json에 대해'wb '대신'w '를 호출해야하기 때문에 두 번째 오류입니다. –