-
Notifications
You must be signed in to change notification settings - Fork 0
/
scrapper2.py
384 lines (310 loc) · 11.4 KB
/
scrapper2.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
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
import requests
from bs4 import BeautifulSoup
import urllib3
import csv
import re
import json
import time
import datetime
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
headers = {
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 '
'(KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
domain = "https://itra.run"
now = datetime.datetime.today()
dateMin = now.strftime('%d/%m/%Y')
dateMax = datetime.datetime(day = now.day, month = now.month, year=now.year + 1).strftime('%d/%m/%Y')
print (dateMin)
print (dateMax)
def _tmp(val):
if val == "":
return False
else:
return True
def showEvt(*args):
return args
def parse_inner2(url):
session = requests.Session()
session.max_redirects = 9999999
dct = {}
# url = url.strip('"')
page = session.get(url,headers=headers, verify=False)
soup = BeautifulSoup(page.content, "html.parser")
Event = soup.select_one("div#calevt_titre").contents[-1].strip()
Race = soup.select_one("div#race-container h2").contents[-1].strip() #get_text(strip=True)
WEBSITE = soup.select_one("div#calevt_titre > div > a.web", href = True)
img_url = soup.select_one("div#im-container a", href = True)
All_info = soup.select("div#calevt_fich tr") #get_text(strip=True)
lst_1 = []
dct_2 = {}
registr_url = ""
for info in All_info:
tds = info.select("td")
if len(tds) == 2:
dct_2[tds[0].get_text().strip()] = tds[1].get_text().strip()
elif len(tds) == 1:
if tds[0].get_text().strip() != "":
if tds[0].select_one("a", href = True) is not None:
registr_url = tds[0].select_one("a", href = True)["href"]
else:
lst_1.append(tds[0].get_text().strip())
try:
registr_fee = lst_1[lst_1.index("Registration fees")+1]
except ValueError:
registr_fee = ""
try:
registr_open = dct_2["Opening of registration"]
except:
registr_open = ""
try:
registr_close = dct_2["Closure of registration"]
except:
registr_close = ""
date_time = dct_2["Date and time of start"].split()
starting_time = date_time.pop().strip()
location_start = dct_2["Location of start"].split()
date = " ".join(date_time)
try:
starting_point = location_start[0]
except:
starting_point = ""
try:
country = re.search(r'\((.*?)\)', dct_2["Location of start"].strip()).group(1)
except:
country = ""
try:
distance = re.sub('[(){}<>]', '', dct_2["Distance"]).split()[0].strip()
except:
distance = ""
try:
elevation_gain = dct_2["Ascent"].strip()
except:
elevation_gain = ""
try:
descent = dct_2["Descent"].strip()
except:
descent = ""
try:
refreshment_points = dct_2["Refreshment points"].strip()
except:
refreshment_points = ""
try:
time_limit = dct_2["Maximum time"].strip()
except:
time_limit = ""
source_url = url
try:
course_url = soup.select_one("div#calevt_fich iframe", src = True)["src"]
except:
course_url = ""
try:
participants = dct_2["Number of participants"].strip()
except:
participants = ""
description = soup.select("div.content p")
Description = ""
if len(description) != 0:
for c, desc in enumerate(description):
if c == 1:
Description += "\nDescription in English\n"
Description += desc.get_text()
else:
Description = ""
if img_url is not None:
img_url = domain + img_url["href"]
else:
img_url = ""
if WEBSITE is not None:
WEBSITE = WEBSITE["href"]
else:
WEBSITE = ""
logo = soup.select_one("div#calevt_lst img", src = True)
if logo is not None:
logo_url = logo["src"]
else:
logo_url = ""
th = soup.select_one("div#calevt_fich tr th", onclick = True)
if th is not None:
stage = th.select_one("a.rightarr", onclick = True)
params = eval(stage['onclick'].split(";")[0])
global sum_distance, sum_elevation_gain, sum_descent, sum_refreshment_points, sum_time_limit
sum_distance = sum_elevation_gain = sum_descent = sum_refreshment_points = sum_time_limit = 0
try:
sum_distance = reprDist(distance)[0]
except Exception as ex:
pass
try:
sum_elevation_gain = reprDist(elevation_gain)[0]
except Exception as ex:
pass
try:
sum_descent = reprDist(descent)[0]
except Exception as ex:
pass
try:
sum_refreshment_points = reprDist(refreshment_points)[0]
except Exception as ex:
pass
try:
sum_time_limit = get_sec(time_limit)
except Exception as ex:
sum_time_limit = 0
pass
calcSUMS(params)
sum_time_limit = get_str(sum_time_limit)
else:
sum_distance = distance
sum_elevation_gain = elevation_gain
sum_descent = descent
sum_refreshment_points = refreshment_points
sum_time_limit = time_limit
dct["Event"] = Event
dct["Race"] = Race
dct["Description"] = Description
dct["Participants"] = participants
dct["Registration Opens"] = registr_open
dct["Registration Closes"] = registr_close
dct["Entry Fee"] = registr_fee
dct["Sign Up"] = registr_url
dct["Date"] = date
dct["Starting Time"] = starting_time
dct["Starting Point"] = starting_point
dct["Country"] = country
dct["SumDistance"] = sum_distance
dct["SumElevation Gain"] = sum_elevation_gain
dct["SumDescent"] = sum_descent
dct["SumRefreshment Points"] = sum_refreshment_points
dct["SumTimeLimit"] = sum_time_limit #
dct["Website"] = WEBSITE
dct["CourseUrl"] = course_url
# dct["CourseFileName"] = "" #
dct["LogoPicURL"] = logo_url
dct["ProfilePicURL"] = img_url
# dct["ProfilePicFile Name"] = "" #
dct["SourceUrl"] = source_url
return dct
def calcSUMS(params):
global sum_distance, sum_elevation_gain, sum_descent, sum_refreshment_points, sum_time_limit
url = "https://itra.run/calend.php?mode=getEvt&id={}&annee={}&idc={}&idx={}".format(*params)
session = requests.Session()
session.max_redirects = 9999999
dct = {}
# url = url.strip('"')
page = session.get(url,headers=headers, verify=False)
soup = BeautifulSoup(page.content, "html.parser")
All_info = soup.select("div#calevt_fich tr") #get_text(strip=True)
lst_1 = []
dct_2 = {}
for info in All_info:
tds = info.select("td")
if len(tds) == 2:
dct_2[tds[0].get_text().strip()] = tds[1].get_text().strip()
elif len(tds) == 1:
if tds[0].get_text().strip() != "":
if tds[0].select_one("a", href = True) is not None:
registr_url = tds[0].select_one("a", href = True)["href"]
else:
lst_1.append(tds[0].get_text().strip())
try:
distance = re.sub('[(){}<>]', '', dct_2["Distance"]).split()[0].strip()
except:
distance = ""
try:
elevation_gain = dct_2["Ascent"].strip()
except:
elevation_gain = ""
try:
descent = dct_2["Descent"].strip()
except:
descent = ""
try:
refreshment_points = dct_2["Refreshment points"].strip()
except:
refreshment_points = ""
try:
time_limit = dct_2["Maximum time"].strip()
except:
time_limit = ""
sum_distance += reprDist(distance)[0]
sum_elevation_gain += reprDist(elevation_gain)[0]
sum_descent += reprDist(descent)[0]
sum_refreshment_points += reprDist(refreshment_points)[0]
sum_time_limit += get_sec(time_limit)
th = soup.select_one("div#calevt_fich tr th", onclick = True)
if th is not None:
try:
stage = th.select_one("a.rightarr", onclick = True)
params = eval(stage['onclick'].split(";")[0])
calcSUMS(params)
except:
return 1
def get_sec(time_str):
_lst = time_str.split(':')
if len(_lst) == 3:
h, m, s = _lst
return int(h) * 3600 + int(m) * 60 + int(s)
elif len(_lst) == 2:
h = 0
m, s = _lst
return int(h) * 3600 + int(m) * 60 + int(s)
else:
return 0
def get_str(time_sec):
if time_sec >= 3600:
return time.strftime('%H:%M:%S', time.gmtime(time_sec))
else:
return time.strftime('%M:%S', time.gmtime(time_sec))
def reprDist(val):
retval = float(re.findall(r"[-+]?\d*\.\d+|\d+", val)[0])
unit = val.replace(re.findall(r"[-+]?\d*\.\d+|\d+", val)[0], "").strip()
return retval, str(retval)+unit
def parse_inner(lst_item):
urls = []
url = "https://itra.run/calend.php?ide={0}&mode=getEvt&id={0}&annee={1}&opendirect=1".format(*lst_item)
session = requests.Session()
page = session.get(url, headers=headers, verify=False)
soup = BeautifulSoup(page.content, "html.parser")
race_params = [eval(i['onclick'].split(";")[0]) for i in soup.select("div#calevt_lst a", href = True)]
for race_param in race_params:
sub_url = "https://itra.run/calend.php?ide={0}&mode=getEvt&id={0}&annee={1}&idc={2}".format(*race_param)
urls.append(sub_url)
return urls
def number_of_pages(main_url):
session = requests.Session()
session.max_redirects = 9999999
page = session.get(main_url.format(1, dateMin, dateMax), headers=headers, verify=False)
soup = BeautifulSoup(page.content, "html.parser")
nbpmax = soup.select_one("script").get_text().strip().split()[-2]
nbpmax = int(re.findall(r"[-+]?\d*\.\d+|\d+", nbpmax)[0])
return nbpmax
def parse_content(url, pageNo):
lst = []
session = requests.Session()
session.max_redirects = 9999999
page = requests.post(url, headers = headers, data = {'num_page': pageNo})
soup = BeautifulSoup(page.text, "html.parser")
Params = soup.select("div.race a", href = True)
for param in Params:
params = eval(param["onclick"].split(";")[0])
lst.append(params)
return lst
PAGE_URL = "https://itra.run/calend.php?mode=getcal&num_page={}&input_cal_rech=&ptsmin=0&ptsmax=6&montmin=0&montmax=14&finishmin=100&finishmax=600&periode=perso&dtmin={}&dtmax={}"
NUMBER_OF_PAGES = number_of_pages(PAGE_URL)
Data_list = []
for page in range(1, NUMBER_OF_PAGES + 1):
URLS = []
url = PAGE_URL.format(page, dateMin, dateMax)
print ("Page ", page)
params = parse_content(url, page)
for param in params:
URLS += parse_inner(param)
print (" Scrapping {} URLS".format(len(URLS)))
for URL in URLS:
Data_list.append(parse_inner2(URL))
fields = ['Event', 'Race', 'Description', 'Participants', 'Registration Opens', 'Registration Closes', 'Entry Fee', 'Sign Up', 'Date', 'Starting Time', 'Starting Point', 'Country', 'SumDistance', 'SumElevation Gain', 'SumDescent', 'SumRefreshment Points', 'SumTimeLimit', 'Website', 'CourseUrl', 'LogoPicURL', 'ProfilePicURL', 'SourceUrl']
with open('scrapped.csv', 'w', encoding="utf-8") as f:
writer = csv.DictWriter(f, fields)
writer.writeheader()
writer.writerows(Data_list)