2012-05-12 10 views
9

장고에서 Scrapy web crawling framework을 실행할 수 있기를 원합니다. Scrapy 자체는 명령을 실행하기 위해 명령 행 도구 scrapy만을 제공합니다. 즉, 도구는 의도적으로 외부 프로그램에서 호출하도록 작성되지 않았습니다.Django 사용자 지정 관리 명령 실행 Scrapy : Scrapy 옵션 포함 방법?

사용자 Mikhail Korobovnice solution으로, 즉 Django 사용자 지정 관리 명령에서 Scrapy를 호출했습니다. 편의를 위해 다음과 같이 솔루션을 반복합니다.

# -*- coding: utf-8 -*- 
# myapp/management/commands/scrapy.py 

from __future__ import absolute_import 
from django.core.management.base import BaseCommand 

class Command(BaseCommand): 

    def run_from_argv(self, argv): 
     self._argv = argv 
     return super(Command, self).run_from_argv(argv) 

    def handle(self, *args, **options): 
     from scrapy.cmdline import execute 
     execute(self._argv[1:]) 

scrapy crawl domain.com 이제 Django 프로젝트에서 python manage.py scrapy crawl domain.com을 할 수 있습니다. 그러나 Scrapy 명령의 옵션은 전혀 구문 분석되지 않습니다.

Usage: manage.py scrapy [options] 

manage.py: error: no such option: -o 

그래서 제 질문은, 어떻게 Scrapy의 명령 줄 옵션을 채택 할 수있는 사용자 지정 관리 명령을 확장 할 수있다 : 나는 python manage.py scrapy crawl domain.com -o scraped_data.json -t json을한다면, 나는 단지 다음과 같은 응답을 얻을?

불행히도 Django의 documentation of this part은 그다지 광범위하지 않습니다. 또한 파이썬의 optparse module에 대한 문서를 읽었지만 후에 나에게 분명하지 않았습니다. 이 점에서 누구든지 나를 도울 수 있습니까? 많은 감사드립니다!

+0

하지만 우리가 크롤링 할 최상위 디렉토리에 있지 않아야합니까 ?? 어떻게 된거 야? @pemistahl – Nabin

답변

5

그래, 내 문제에 대한 해결책을 찾았습니다. 약간 추한 것이지만 작동합니다. Django 프로젝트의 manage.py 명령은 Scrapy의 명령 행 옵션을 허용하지 않기 때문에, 옵션 문자열을 manage.py에 의해 허용되는 두 개의 인수로 분할합니다. 구문 분석에 성공한 후에 저는 두 가지 주장을 다시 병합하여 Scrapy에 전달합니다. 대신

python manage.py scrapy crawl domain.com -o scraped_data.json -t json 

내가이

python manage.py scrapy crawl domain.com - o scraped_data.json - t json 

내 핸들 기능과 같은 옵션 사이에 띄어쓰기를 작성한다

은 다음과 같습니다

def handle(self, *args, **options): 
    arguments = self._argv[1:] 
    for arg in arguments: 
     if arg in ('-', '--'): 
      i = arguments.index(arg) 
      new_arg = ''.join((arguments[i], arguments[i+1])) 
      del arguments[i:i+2] 
      arguments.insert(i, new_arg) 

    from scrapy.cmdline import execute 
    execute(arguments) 

한편, Mikhail Korobov는 최적의 솔루션을 제공했습니다. 여기를 참조하십시오 :

# -*- coding: utf-8 -*- 
# myapp/management/commands/scrapy.py 

from __future__ import absolute_import 
from django.core.management.base import BaseCommand 

class Command(BaseCommand): 

    def run_from_argv(self, argv): 
     self._argv = argv 
     self.execute() 

    def handle(self, *args, **options): 
     from scrapy.cmdline import execute 
     execute(self._argv[1:]) 
3

난 당신이 정말 가이드 라인 POSIX argument syntax conventions 10 찾고있는 생각 :

인수 - 옵션의 끝을 나타내는 구분 기호로 인정되어야한다. 다음 인수는 모두 '-'문자 인 으로 시작하는 경우에도 피연산자로 처리해야합니다. - 인수는 옵션이나 피연산자로 사용하면 안됩니다.

파이썬의 optparse 모듈은 창 아래에서도 이런 식으로 동작합니다.

나는 인수 목록에서 scrapy 프로젝트 설정 모듈을 넣어, 그래서 나는 독립적 인 응용 프로그램에 별도의 scrapy 프로젝트를 만들 수 있습니다

# <app>/management/commands/scrapy.py 
from __future__ import absolute_import 
import os 

from django.core.management.base import BaseCommand 

class Command(BaseCommand): 
    def handle(self, *args, **options): 
     os.environ['SCRAPY_SETTINGS_MODULE'] = args[0] 
     from scrapy.cmdline import execute 
     # scrapy ignores args[0], requires a mutable seq 
     execute(list(args)) 

를 호출 다음과 같이

python manage.py scrapy myapp.scrapyproj.settings crawl domain.com -- -o scraped_data.json -t json 

가 scrapy 0.12으로 테스트 장고 1.3.1