-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscrapystreaming.py
executable file
·64 lines (48 loc) · 1.78 KB
/
scrapystreaming.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/python2
import sys
from twisted.internet.defer import Deferred
from twisted.internet import reactor
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
from scrapy.settings import Settings
from streamingspider import StreamingSpider
from linereceiverprocess import Communicate
from utils import deserializeLine
class ScrapyStreaming():
def __init__(self, cmd):
self.cmd = cmd.split()
self.process = Communicate()
self.dfds = []
dfd = Deferred()
dfd.addCallback(deserializeLine)
dfd.addCallback(self.generateSpider)
dfd.addCallback(self.runSpider)
reactor.callLater(0, self.process.start, self.cmd, self.lineReceived,
self.connectionLost)
reactor.callLater(0, self.getLine, dfd)
reactor.run()
def lineReceived(self, line):
self.dfds.pop().callback(line)
def connectionLost(self, reason):
pass
def getLine(self, dfd):
self.dfds.append(dfd)
def sendLine(self, line):
self.process.send(line)
def generateSpider(self, settings):
class Spider(StreamingSpider):
name = settings['name']
process = self
allowed_domains = settings['allowed_domains']
start_urls = settings['start_urls']
return Spider
def runSpider(self, spider):
configure_logging({'LOG_FORMAT': '%(asctime)s [%(name)s] %(levelname)s: %(message)s'})
settings = Settings()
settings.set('FEED_URI', 'output.json')
settings.set('FEED_FORMAT', 'json')
runner = CrawlerRunner(settings)
dfd = runner.crawl(spider)
dfd.addBoth(lambda _: reactor.stop())
if __name__ == '__main__':
ScrapyStreaming(sys.argv[1])