forked from ldulcic/njuskalo-scraper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
71 lines (54 loc) · 1.95 KB
/
main.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
65
66
67
68
69
70
#!/usr/bin/env python3 -u
import argparse
import schedule
import time
import multiprocessing as mp
from scrapy.crawler import CrawlerProcess, Crawler
from scrapy import signals
from scrapy.utils.project import get_project_settings
from njuskalo_scraper.spiders.njuskalo_spider import NjuskaloSpider
from njuskalo_scraper.database import init_database, NjuskaloAdDB
from njuskalo_scraper.util import MailSender, parse_urls_file
mail_sender = MailSender()
def _crawl(queue, urls):
items_scraped = []
def item_scraped(item, response, spider):
items_scraped.append(item)
process = CrawlerProcess(get_project_settings())
crawler = Crawler(NjuskaloSpider, get_project_settings())
crawler.signals.connect(item_scraped, signals.item_scraped)
process.crawl(crawler, start_urls=urls)
process.start()
queue.put(items_scraped)
def crawl(urls=None, first_run=False):
q = mp.Queue()
p = mp.Process(target=_crawl, args=(q, urls))
p.start()
items_scraped = q.get()
p.join()
if not first_run and items_scraped:
mail_sender.send_email(items_scraped)
def parse_urls():
args = argparse.ArgumentParser()
group = args.add_mutually_exclusive_group(required=True)
group.add_argument('-u', '--urls', help='Comma separated njuskalo urls to scrape.')
group.add_argument('-f', '--file', help='Path to file with urls. Every line of file contains njuskalo url.')
args = args.parse_args()
if args.urls:
return list(map(lambda url: url.strip(), args.urls.split(',')))
else:
return parse_urls_file(args.file)
def main():
init_database()
urls = parse_urls()
crawl(urls, first_run=not NjuskaloAdDB.select().exists())
schedule.every(20).minutes.do(crawl, urls=urls)
while True:
try:
schedule.run_pending()
time.sleep(1)
except KeyboardInterrupt:
print("Stopping crawler...")
break
if __name__ == '__main__':
main()