-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathscraper.py
52 lines (42 loc) · 1.47 KB
/
scraper.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
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import threading
import requests
from utils import get_module_logger
logger = get_module_logger(__name__)
class Scraper(threading.Thread):
def __init__(self, url, result):
super(Scraper, self).__init__()
self.name = "thread-%s" % url
self.url = url
self.result = result
def run(self):
result = []
try:
s = requests.session()
response = s.get(self.url, timeout=5)
except Exception as e:
logger.warning("Get {0} failed, error: {1}.".format(self.url, str(e)))
else:
if response.status_code != requests.codes.ok:
logger.warning("Get {0} failed, response code is: {1}.".format(self.url, response.status_code))
else:
rlt = response.json()
if rlt and "beans" in rlt:
result = rlt['beans']
else:
logger.warning("No metrics get in the {0}.".format(self.url))
s.close()
if len(result) > 0:
self.result.append(result)
class ScrapeMetrics(object):
def __init__(self, urls):
self.urls = urls
def scrape(self):
result = []
tasks = [Scraper(url, result) for url in self.urls]
for task in tasks:
task.start()
for task in tasks:
task.join()
return result