-
Notifications
You must be signed in to change notification settings - Fork 0
/
scraper_12th23.py
567 lines (534 loc) · 14.8 KB
/
scraper_12th23.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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
from colorama import Fore, Back, Style, init
import json
import requests
from bs4 import BeautifulSoup
import mysql.connector
from prettytable import PrettyTable
import argparse
import datetime
conn = mysql.connector.connect(
host='localhost',
user='root',
password='',
database='upboard'
)
cursor = conn.cursor()
def check_roll_number_exist(roll_number):
cursor.execute("SELECT COUNT(*) FROM studentinfo12th2023 WHERE rollno = %s", (roll_number,))
result = cursor.fetchone()[0]
return result > 0
def insert_student_info_and_subjects(roll_number, name, father, mother, dob, school, subjects):
cursor.execute("INSERT INTO studentinfo12th2023 (rollno, name, father, mother, dob, school) VALUES (%s, %s, %s, %s, %s, %s)",
(roll_number, name, father, mother, dob, school))
for subject_info in subjects:
subject = subject_info['subject']
mark = subject_info['mark']
practical = subject_info['practical']
total = subject_info['total']
grade = subject_info['grade']
cursor.execute("INSERT INTO studentsubjects12th2023(rollno, subjects, mark, practical, total, grade) "
"VALUES (%s, %s, %s, %s, %s, %s)",
(roll_number, subject, mark, practical, total, grade))
conn.commit()
print(f"{Fore.GREEN}{name} {roll_number} inserted successfully.{Style.RESET_ALL}")
def getstudent(cursor, rollno):
rows=[]
query = "SELECT * FROM studentinfo12th2023 WHERE rollno = %s"
cursor.execute(query, (rollno,))
row = cursor.fetchone()
rows.append(row)
# query = "SELECT * FROM studentsubjects12th2023 WHERE rollno = %s"
# cursor.execute(query, (rollno,))
# row = cursor.fetchone()
# rows.append(row)
if row:
return row
else:
return None
def getmarks(cursor, rollno):
query = "SELECT subjects,mark,practical,total,grade FROM studentsubjects12th2023 WHERE rollno = %s"
cursor.execute(query, (rollno,))
row = cursor.fetchall()
if row:
return row
else:
return None
def validate_start_end_order(start, end):
if start >= end:
raise argparse.ArgumentTypeError("--start value must be lower than --end value")
def validate_std(value):
if value not in ['10', '12']:
raise argparse.ArgumentTypeError("--std must be '10' or '12'")
else:
return int(value)
def validate_dist(value):
try:
value = int(value)
if not (0 < value < 100):
raise argparse.ArgumentTypeError("--dist must be less than 100")
return value # Return the validated integer
except ValueError:
raise argparse.ArgumentTypeError("--dist must be an integer")
def find_name_by_dist(data, target_dist):
for entry in data:
name, code = entry
if code == target_dist:
return name
return None # Return None if no match is found
def validate_year(value):
try:
year = int(value)
current_year = datetime.datetime.now().year
if not (1921 <= year <= current_year):
raise argparse.ArgumentTypeError(f"--year must be in the range 1921 to {current_year}")
else:
return year
except ValueError:
raise argparse.ArgumentTypeError("--year must be an integer")
def validate_int(value):
try:
return int(value)
except ValueError:
raise argparse.ArgumentTypeError(f"{value} must be an integer")
def main():
# Create ArgumentParser object
parser = argparse.ArgumentParser(description='Uttar Pradesh Board Examination Result scraper.')
# Add required command-line arguments
parser.add_argument('--start', type=validate_int, required=True, help='First Roll no to Scrape')
parser.add_argument('--end', type=validate_int, required=True, help='Last Roll Number to scrape in Range')
parser.add_argument('--dist', type=validate_dist, required=True, help='District Code')
parser.add_argument('--std', type=validate_std, required=True, help='Your Class 10[High School] 12[Intermediate]')
parser.add_argument('--year', type=validate_year, required=True, help='Year [Board Exam Year]')
data_array = [
[
"AGRA",
1
],
[
"ALIGARH",
6
],
[
"AMBEDKAR NAGAR",
64
],
[
"AMETHI",
65
],
[
"AMROHA",
22
],
[
"AURIYA",
43
],
[
"AYODHYA",
62
],
[
"AZAMGARH",
80
],
[
"BAGPAT",
13
],
[
"BAHRAICH",
66
],
[
"BALLIA",
82
],
[
"BALRAMPUR",
69
],
[
"BANDA",
51
],
[
"BARABANKI",
63
],
[
"BAREILLY",
26
],
[
"BASTI",
71
],
[
"BHADOHI",
88
],
[
"BIJNOR",
23
],
[
"BUDAUN",
27
],
[
"BULANDSHAHR",
9
],
[
"CHANDAULI",
86
],
[
"CHITRAKOOT",
52
],
[
"DEORIA",
77
],
[
"ETAH",
4
],
[
"ETAWAH",
41
],
[
"FARRUKHABAD",
40
],
[
"FATEHPUR",
56
],
[
"FIROZABAD",
2
],
[
"GAUTAM BUDH NAGAR",
11
],
[
"GHAZIABAD",
10
],
[
"GHAZIPUR",
84
],
[
"GONDA",
68
],
[
"GORAKHPUR",
75
],
[
"HAMIRPUR",
49
],
[
"HAPUR",
14
],
[
"HARDOI",
33
],
[
"HATHRAS",
7
],
[
"JALAUN",
45
],
[
"JAUNPUR",
83
],
[
"JHANSI",
47
],
[
"KANNAUJ",
42
],
[
"KANPUR DEHAT",
39
],
[
"KANPUR NAGAR",
38
],
[
"KASGANJ",
8
],
[
"KAUSHAMBI",
57
],
[
"KUSHINAGAR",
78
],
[
"LAKHIMPUR KHIRI",
31
],
[
"LALITPUR",
48
],
[
"LUCKNOW",
34
],
[
"MAHARAJGANJ",
76
],
[
"MAHOBA",
50
],
[
"MAINPURI",
3
],
[
"MATHURA",
5
],
[
"MAU",
81
],
[
"MEERUT",
12
],
[
"MIRZAPUR",
89
],
[
"MORADABAD",
21
],
[
"MUZAFFAR NAGAR",
15
],
[
"PILIBHIT",
29
],
[
"PRATAPGARH",
54
],
[
"PRAYAGRAJ",
55
],
[
"RAE BARAILI",
36
],
[
"RAMPUR",
24
],
[
"SAMBHAL",
25
],
[
"SANT KABIR NAGAR",
72
],
[
"SHAHARANPUR",
16
],
[
"SHAHJAHANPUR",
28
],
[
"SHAMLI",
17
],
[
"SHRAWASTI",
67
],
[
"SIDDHARTA NAGAR",
73
],
[
"SITAPUR",
32
],
[
"SONBHADRA",
90
],
[
"SULTANPUR",
61
],
[
"UNNAO",
35
],
[
"VARANASI",
85
]
]
try:
args = parser.parse_args()
district=find_name_by_dist(data_array, args.dist)
try:
def getresult(rollno):
if check_roll_number_exist(rollno):
studentdata=getstudent(cursor,rollno)
table = PrettyTable([Fore.YELLOW + 'Roll Number' + Style.RESET_ALL,
Fore.YELLOW + 'Name' + Style.RESET_ALL,
Fore.YELLOW + 'Father' + Style.RESET_ALL,
Fore.YELLOW + 'Mother' + Style.RESET_ALL,
Fore.YELLOW + 'DOB' + Style.RESET_ALL,
Fore.YELLOW + 'School' + Style.RESET_ALL])
colored_data = [Fore.WHITE + str(data) + Style.RESET_ALL for data in studentdata]
table.add_row(colored_data)
print(table)
studentmarks=getmarks(cursor,rollno)
table = PrettyTable([Fore.GREEN + 'Subject' + Style.RESET_ALL,
Fore.GREEN + 'Subjective' + Style.RESET_ALL,
Fore.GREEN + 'Practical' + Style.RESET_ALL,
Fore.GREEN + 'Total' + Style.RESET_ALL,
Fore.GREEN + 'Grade' + Style.RESET_ALL])
for studentmark in studentmarks:
table.add_row(studentmark)
print(table)
else:
if rollno is None:
raise ValueError("Parameter 'Roll Number' must be provided.")
form_url='https://results.upmsp.edu.in/ResultIntermediate.aspx'
response = requests.get(form_url)
html_content = response.text
soup = BeautifulSoup(html_content, 'html.parser')
inputs=soup.find_all("input")
dataa=[]
for inpu in inputs:
name=inpu.get("name")
value=inpu.get("value")
d=[]
if name:
if name=="ctl00$cphBody$txt_RollNumber":
value=rollno
d.append(name)
d.append(value)
dataa.append(d)
k=[]
k.append("ctl00$cphBody$ddl_ExamYear")
k.append("2023")
dataa.append(k)
k=[]
k.append("ctl00$cphBody$ddl_districtCode")
k.append("45")
dataa.append(k)
payload=dict(dataa)
response = requests.post(form_url, data=payload)
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'html.parser')
table = soup.find("table")
if table:
name_element = table.find('span', id='ctl00_cphBody_lbl_C_NAME')
mother_element = table.find('span', id='ctl00_cphBody_lbl_M_NAME')
father_element = table.find('span', id='ctl00_cphBody_lbl_F_NAME')
# dob_element = table.find('span', id='ctl00_cphBody_lbl_DDMMYYYY')
school_element = table.find('span', id='ctl00_cphBody_lbl_SCHOOL_CD')
if name_element.text!="" and mother_element.text!="" and father_element.text!="":
name = name_element.text if name_element else None
mother = mother_element.text if mother_element else None
father = father_element.text if father_element else None
# dob = dob_element.text if dob_element else None
school = school_element.text if school_element else None
dob="Not Find"
result = []
rows = table.find_all("tr")
ille=True
for row in rows:
if ille:
ille=False
continue
col = row.find_all("td")
if len(col) == 8:
sub = {
"subject": col[0].find("span").text if col[0].find("span") else None,
"mark": col[1].find("span").text if col[1].find("span") else None,
"practical": col[6].find("span").text if col[6].find("span") else None,
"total": col[7].find("span").text if col[7].find("span") else None,
"grade": "N/A",
}
if all(value is not None for value in sub.values()):
result.append(sub)
stude={
"name": name,
"mother": mother,
"father": father,
"dob": dob,
"school": school,
}
student_data = {
"student": stude,
"results": result
}
if not check_roll_number_exist(rollno):
insert_student_info_and_subjects(rollno, **stude, subjects=result)
else:
print(f"{Fore.RED}{name} {rollno} [already exists]{Style.RESET_ALL}")
formatted_json = json.dumps(student_data, indent=4)
# print(formatted_json)
else:
print(f"{Fore.RED}{rollno} is not a valid Roll Number.{Style.RESET_ALL}")
else:
print(f"{Fore.RED}Error in Load.{Style.RESET_ALL}")
if rollno<args.end:
getresult(rollno+1)
def validate_input(roll_no):
try:
# Try to convert the input to an integer
roll_no = int(roll_no)
# Check if the length is exactly 10 digits
if len(str(roll_no)) == 10:
return roll_no
else:
print(f"{Fore.YELLOW}Roll number must be an integer of length 10.{Style.RESET_ALL}")
return None
except ValueError:
print(f"{Fore.YELLOW}Roll number must be an integer.{Style.RESET_ALL}")
return None
getresult(args.start)
except KeyboardInterrupt:
print(f"{Fore.BLUE}\nCtrl+C pressed. Exiting gracefully.{Style.RESET_ALL}")
except argparse.ArgumentTypeError as e:
print(f"Error: {e}")
if __name__ == '__main__':
main()