2017-12-27 3 views
1

저는 Scrapy를 처음 사용하고 다음을 시도하고 있습니다. 웹 페이지에서 일부 값을 추출하여 변수에 저장하고 주 스크립트에서 사용합니다. 그러므로 나는 그들의 튜토리얼을 따라 내 목적을 위해 코드를 변경 : 이것은 지금까지 일하는 것이Scrapy store가 주 스크립트에서 사용할 변수를 반환했습니다.

import scrapy 
from scrapy.crawler import CrawlerProcess 


class QuotesSpider(scrapy.Spider): 
    name = "quotes" 
    start_urls = [ 
     'http://quotes.toscrape.com/page/1/' 
    ] 

    custom_settings = { 
     'LOG_ENABLED': 'False', 
    } 

    def parse(self, response): 
     global title # This would work, but there should be a better way 
     title = response.css('title::text').extract_first() 

process = CrawlerProcess({ 
    'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)' 
}) 

process.crawl(QuotesSpider) 
process.start() # the script will block here until the crawling is finished 

print(title) # Verify if it works and do some other actions later on... 

,하지만 난 그게 좋은 스타일이 아니거나 심지어 내가 제목을 정의하면 나쁜 부작용이 확신 글로벌 변수. 그 행을 건너 뛰면 물론 "정의되지 않은 변수"오류가 발생합니다./ 따라서 변수를 반환하고 내 주 스크립트에서 사용하는 방법을 찾고 있습니다.

항목 파이프 라인에 대해 읽었지만 제대로 작동하지 못했습니다.

도움말/아이디어는 크게 감사드립니다. 미리 감사드립니다!

+1

를보다 효율적으로 사용하는'global'을 - 쉽게 될 것입니다. 파이프 라인이 도움이되지 않습니다. – furas

답변

1

당신이 알고있는대로 당신이 알고있는대로, 특히 당신이 당신의 요구를 확장해야 할 때.

나의 제안은 파일 또는 목록에 제목을 저장하고 주요 공정에서 사용하는 것입니다, 또는 당신은 다른 스크립트의 제목, 다음 열어 파일을 처리하고 (스크립트

을에서 제목을 읽으려면 참고 :) 들여 쓰기 문제를 무시하세요

spider.py

import scrapy 
from scrapy.crawler import CrawlerProcess 

namefile = 'namefile.txt' 
current_title_session = []#title stored in current session 
file_append = open(namefile,'a',encoding = 'utf-8') 

try: 
    title_in_file = open(namefile,'r').readlines() 
except: 
    title_in_file = open(namefile,'w') 

class QuotesSpider(scrapy.Spider): 
    name = "quotes" 
    start_urls = [ 
     'http://quotes.toscrape.com/page/1/' 
    ] 

    custom_settings = { 
     'LOG_ENABLED': 'False', 
    } 

    def parse(self, response): 
     title = response.css('title::text').extract_first() 
     if title +'\n' not in title_in_file and title not in current_title_session: 
      file_append.write(title+'\n') 
      current_title_session.append(title) 
if __name__=='__main__': 
    process = CrawlerProcess({ 
     'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)' 
    }) 

    process.crawl(QuotesSpider) 
    process.start() # the script will block here until the crawling is finished 
+0

잘 모르겠지만 고마워요, 이것이 글로벌 진술로 문제를 해결합니다. 파일을 처리하기 위해 다른 파일을 만드는 것이 우아하다면. 어쨌든 - 이것은 나를 위해 잘 작동합니다 :-) – MaGi

2

변수를 만들면 global이 필요합니다.하지만 언급 한 것처럼 좋은 스타일은 아닙니다.

실제로 프로세스 간의 통신에 다른 서비스를 사용하는 것이 좋습니다 (예 : Redis). 따라서 거미와 다른 프로세스간에 충돌이 발생하지 않도록 할 수 있습니다.

설치 및 사용이 매우 간단하며 설명서에는 very simple example이 있습니다.

스파이더 내부와 주 프로세스에서 다시 연결을 인스턴스화합니다 (별개의 프로세스로 생각하십시오). 거미가 변수를 설정하고 주 프로세스가 정보를 읽습니다 (또는 get s).

+0

고마워요, 단기간에, 나는 furas와 AndyWangs의 대답으로 갈 것입니다. 그러나 시간이 있다면 Redis로 읽어 보겠습니다 :) – MaGi

관련 문제