json 데이터를 크롤러에서 보내고 결과를 가져올 수 있습니다. 다음과 같이 수행 할 수 있습니다 :
class MySpider(scrapy.Spider):
# some attributes
accomulated=[]
def parse(self, response):
# do your logic here
page_text = response.xpath('//text()').extract()
for text in page_text:
if conditionsAreOk(text):
self.accomulated.append(text)
def closed(self, reason):
# call when the crawler process ends
print JSON.dumps(self.accomulated)
이 같은 runner.py 스크립트를 작성 :
import sys
from twisted.internet import reactor
import scrapy
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
from scrapy.utils.project import get_project_settings
from spiders import MySpider
def main(argv):
url = argv[0]
configure_logging({'LOG_FORMAT': '%(levelname)s: %(message)s', 'LOG_ENABLED':False })
runner = CrawlerRunner(get_project_settings())
d = runner.crawl(MySpider, url=url)
# For Multiple in the same process
#
# runner.crawl('craw')
# runner.crawl('craw2')
# d = runner.join()
d.addBoth(lambda _: reactor.stop())
reactor.run() # the script will block here until the crawling is finished
if __name__ == "__main__":
main(sys.argv[1:])
그리고 같은 main.py에서 호출 :
는 거미를 갖는
import json, subprocess, sys, time
def main(argv):
# urlArray has http:// or https:// like urls
for url in urlArray:
p = subprocess.Popen(['python', 'runner.py', url ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
# do something with your data
print out
print json.loads(out)
# This just helps to watch logs
time.sleep(0.5)
if __name__ == "__main__":
main(sys.argv[1:])
이것은 알고있는 것처럼 Scrapy를 사용하는 최선의 방법은 아니지만 복잡한 후 처리가 필요없는 빠른 결과를 위해이 솔루션은 필요한 것을 제공 할 수 있습니다.
도움이되기를 바랍니다.
심각한 해킹이 없으면 main.py를 비동기로 사용해야 할 방법이 없습니다. 왜'scrap crawl myspider -o items.json' 파일을 크롤링하지 않고'main.py' 파일에서 반복합니다. 또는 이상적으로 전체 main.py 로직을 거미 자체로 옮기시겠습니까? – Granitosaurus