import os import csv import pickle import logging import asyncio impor

  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
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
import os
import csv
import pickle
import logging
import asyncio
import aiohttp
import signal
from time import time
from datetime import datetime
from pyquery import PyQuery
HOST = 'http://itsell.com.ua'
LOGLEVEL = logging.INFO
SESSION_FILE = 'cache.pickle'
def parse_catalogue_list(html: str):
results = []
d = PyQuery(html)
links = d('.category-filter-block a')
for link in links.items():
url = link.attr.href.strip()
logging.debug('{}'.format(url))
results.append(url)
return results
def parse_goods_list(html: str):
r = {
'next_page': None,
'urls': [],
}
d = PyQuery(html)
product_links = d('.promotional-image-block a')
if len(product_links) > 0:
# parse links
for product_link in product_links.items():
r['urls'].append(product_link.attr.href.strip())
# parse next page
next_page = d('.pagination a:last').attr.href
if next_page:
r['next_page'] = HOST + next_page
return r
def parse_product(html: str):
d = PyQuery(html)
photos = [HOST + x.attr.href for x in d('.product-preview-photo a').items()]
colors = [x.tail.strip() for x in d('.product-color-select-item span')]
r = {
'category1': d('.product-path-block .wrapper a span').eq(0).text(),
'category2': d('.product-path-block .wrapper a span').eq(1).text(),
'name': d('.product-name').text(),
'cost': d('.product-price span').text(),
'description': d('.characteristics-block .post-description').html(),
'photos': ','.join(photos),
'colors': ','.join(colors),
}
return {k: (v or '').strip() for k, v in r.items()}
class Crawler:
def __init__(self, loop, maxtasks=10):
self.sem = asyncio.Semaphore(maxtasks)
self.queue = asyncio.Queue()
self.loop = loop
self.csv_writer = None
self.do = True
self.complete = False
self.connector = aiohttp.TCPConnector(share_cookies=True, loop=loop)
self.session = {}
self.tasks = []
def soft_stop(self):
logging.info("Prepare to stop. Please wait ...")
self.do = False
@asyncio.coroutine
def create_session(self):
html = yield from self.get('http://itsell.com.ua/catalog/raznoe')
catalogue = parse_catalogue_list(html)
self.session['lists'] = catalogue
self.session['items'] = []
self.session['goods'] = 0
self.session['start'] = time()
now_str = datetime.now().strftime('%Y_%m_%d__%H_%M_%S')
self.session['csv_file_name'] = 'goods__{}.csv'.format(now_str)
@asyncio.coroutine
def load_session(self):
logging.info('Try to load saved session')
try:
with open(SESSION_FILE, 'rb') as session_file:
self.session = pickle.load(session_file)
logging.info('Session have been loaded')
except FileNotFoundError:
logging.info("Can't load old session, start a new one")
yield from self.create_session()
def save_session(self):
with open(SESSION_FILE, 'wb') as session_file:
pickle.dump(self.session, session_file)
@asyncio.coroutine
def process_list(self, url):
try:
html = yield from asyncio.wait_for(self.get(url), 60)
except asyncio.TimeoutError:
logging.error("Can't parse url {}".format(url))
return
r = parse_goods_list(html)
if len(r['urls']) < 2:
logging.warning('Url {} has very low goods\' links {}'
.format(url, r))
if r['next_page']:
self.session['lists'].append(r['next_page'])
self.session['items'] += r['urls']
logging.debug('Parsed list {}'.format(url))
@asyncio.coroutine
def process_item(self, url):
try:
html = yield from asyncio.wait_for(self.get(url), 60)
except asyncio.TimeoutError:
logging.error("Can't parse url {}".format(url))
return
r = parse_product(html)
self.csv_writer.writerow([
r['category1'],
r['category2'],
r['name'],
r['cost'],
r['colors'],
r['photos'],
r['description'],
])
self.session['goods'] += 1
logging.debug('Parsed item {}'.format(url))
@asyncio.coroutine
def master(self):
while self.do:
while self.session['items']:
yield from self.sem.acquire()
url = self.session['items'].pop()
task = asyncio.Task(self.process_item(url))
task.add_done_callback(lambda t: self.sem.release())
self.tasks.append(task)
task.add_done_callback(self.tasks.remove)
if self.session['lists']:
yield from self.sem.acquire()
url = self.session['lists'].pop()
task = asyncio.Task(self.process_list(url))
task.add_done_callback(lambda t: self.sem.release())
self.tasks.append(task)
task.add_done_callback(self.tasks.remove)
if not self.session['lists'] and not self.session['items']:
yield from asyncio.gather(*self.tasks)
if not self.session['lists'] and not self.session['items']:
logging.info(self.session)
logging.info(self.tasks)
self.complete = True
self.soft_stop()
break
@asyncio.coroutine
def run(self):
yield from self.load_session()
asyncio.Task(self.master())
with open(self.session['csv_file_name'], 'a') as csv_file:
self.csv_writer = csv.writer(
csv_file,
quoting=csv.QUOTE_MINIMAL,
delimiter=';',
)
while self.do:
yield from asyncio.sleep(7)
logging.info('Goods parsed {}'.format(self.session['goods']))
logging.info('Auto save...')
self.save_session()
while self.tasks:
yield from asyncio.sleep(3)
logging.info('{} tasks still working. Waiting for them done'
.format(len(self.tasks)))
yield from asyncio.gather(*self.tasks)
self.connector.close()
self.loop.stop()
if self.complete:
logging.info("=" * 40)
logging.info("Parsing complete in {} sec"
.format(int(time() - self.session['start'])))
logging.info("=" * 40)
logging.info('Goods parsed {}'.format(self.session['goods']))
os.remove(SESSION_FILE)
logging.debug('Remove cache')
@asyncio.coroutine
def get(self, url):
try:
r = yield from aiohttp.request('get', url, connector=self.connector)
except asyncio.CancelledError:
logging.warning('Task canceled {}'.format(url))
except Exception as e:
logging.exception(e)
else:
if r.status == 200:
logging.debug(r)
data = (yield from r.read()).decode('utf-8', 'replace')
else:
data = None
r.close()
return data
def main():
logging.info('Create event loop')
loop = asyncio.get_event_loop()
logging.info('Init Crawler')
c = Crawler(loop)
loop.add_signal_handler(signal.SIGINT, lambda: c.soft_stop())
loop.run_until_complete(c.run())
loop.close()
if __name__ == "__main__":
logging.basicConfig(level=LOGLEVEL)
main()