-
Notifications
You must be signed in to change notification settings - Fork 2
/
crawl_strava.py
164 lines (124 loc) · 3.99 KB
/
crawl_strava.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
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
import cookielib
import time
import urllib
import urllib2
import re
from BeautifulSoup import BeautifulSoup
import numpy as np
import simplejson as json
TIME_BT_REQUESTS = 2
def fetch_url(url):
try:
print 'fetching %s' % url
response = opener.open(url)
time.sleep(TIME_BT_REQUESTS)
except Exception, e:
print '%s - %s' % (e, url)
time.sleep(TIME_BT_REQUESTS)
return None
if response.getcode() != 200:
raise Exception('%s: %s - %s' % \
(url, response.getcode(), response.msg))
response = response.read()
return response
# authentication code by: https://github.com/loisaidasam/stravalib
def log_in():
print "Logging in..."
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
f = opener.open('https://www.strava.com/login')
soup = BeautifulSoup(f.read())
time.sleep(TIME_BT_REQUESTS)
utf8 = soup.findAll('input', {'name': 'utf8'})[0].get('value').encode('utf-8')
token = soup.findAll('input', {'name': 'authenticity_token'})[0].get('value')
values = {
'utf8': utf8,
'authenticity_token': token,
'email': '<< your email here >>',
'password': '<< your password here >>',
}
data = urllib.urlencode(values)
url = 'https://www.strava.com/session'
response = opener.open(url, data)
soup = BeautifulSoup(response.read())
time.sleep(TIME_BT_REQUESTS)
return opener
athlete_rides = {}
ride_data = {}
def get_athlete_info(opener, athlete_id):
# without these headers, the request doesn't return anything
opener.addheaders = [
('X-Requested-With', 'XMLHttpRequest'),
('Accept',
('text/javascript, application/javascript, application/ecmascript,'
' application/x-ecmascript')
),
]
if athlete_id not in athlete_rides:
rides = []
for interval in ['201606', '201605', '201604']:
url = 'https://www.strava.com/athletes/%s/interval?interval=%s&interval_type=month&chart_type=miles&year_offset=0' \
% (athlete_id, interval)
response = fetch_url(url)
if not response:
continue
response = response.replace(' rode with ', '|separator|')
response = response.replace('app-icon icon-ride icon-sm type', '|separator|')
rides_batch = response.split('|separator|')[1:]
rides_batch = [r.split('/activities/')[1].split('\\')[0] for r in rides_batch]
rides.extend(rides_batch)
athlete_rides[athlete_id] = rides
for ride in athlete_rides[athlete_id]:
if ride not in ride_data:
url = 'https://www.strava.com/activities/%s/streams' % ride
response = fetch_url(url)
if response:
response = json.loads(response)
else:
response = None
f = open('ride_data.json', 'a')
f.write(json.dumps((ride, response)))
f.write('\n')
ride_data[ride] = 1
def get_athletes(club_id):
page = 1
member_ids = []
while True:
url = 'https://www.strava.com/clubs/%s/members?page=%s' % (club_id, page)
response = fetch_url(url)
matches = re.findall('\/athletes\/\d+', response)
member_ids.extend([m.split('/')[2] for m in matches])
if len(matches) < 100:
break
page += 1
return member_ids
def save_data():
data = json.dumps(athletes)
f = open('athletes.json', 'w')
f.write(data)
f.close()
data = json.dumps(athlete_rides)
f = open('athlete_rides.json', 'w')
f.write(data)
f.close()
def load_cache():
athletes = json.loads(open('athletes.json', 'r').read())
athlete_rides = json.loads(open('athlete_rides.json', 'r').read())
ride_data = {}
f = open('ride_data.json', 'r')
while True:
row = f.readline()
if not row:
break
ride_id = row.split('", ')[0][2:]
ride_data[ride_id] = 1
def get_data():
opener = log_in()
clubs = ['38078', '37183', '186539', '126088', '26378', '15443', '35212', '24175', '53666']
athletes = []
for club_id in clubs:
athletes.extend(get_athletes(club_id))
athletes = list(set(athletes))
for athlete in athletes:
get_athlete_info(opener, athlete)
get_data()