-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathleetcodeDownloader.py
executable file
·67 lines (54 loc) · 1.72 KB
/
leetcodeDownloader.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
import leetcodeHTTPHelper
import re
import json
import os
import sys
import getpass
MAX_PAGE = 10000
ADD_FILE = 'add file: '
ALL_SUBMISSIONS_CHECKED = 'All submissions checked.'
CHECK_PAGE = 'Check page '
USAGE = "usage: leetcodeDownloader.py username"
SUBMISSION_URL = 'https://leetcode.com/api/submissions/my/'
BASE_URL = 'https://leetcode.com'
def downloadSubmission(session, name, file_type, URL):
'''
parse code from source and save it to file.
'''
filename = 'code/' + name + '.' + file_type
if os.path.isfile(filename):
return
r = session.get(URL)
code = re.search(r'submissionCode\:\ \'([^\']+)\'', r.content).group(1)
code = code.encode('utf8')
s = json.loads('{"code": "%s"}' % code)
print ADD_FILE + filename
f = open(filename, 'w')
f.write(s['code'])
f.close()
def checkSubmissions(username, password):
s = leetcodeHTTPHelper.login(username, password)
if not os.path.exists('code'):
os.makedirs('code')
for i in range(1, MAX_PAGE):
print CHECK_PAGE + str(i)
r = s.get(SUBMISSION_URL + str(i))
trList = r.json()['submissions_dump']
if(len(trList) == 0):
print ALL_SUBMISSIONS_CHECKED
break
for tr in trList:
result = tr['status_display']
file_type = tr['lang']
if (result == 'Accepted'):
problemName = tr['title']
codeUrl = BASE_URL + tr['url']
downloadSubmission(s, problemName, file_type, codeUrl)
if __name__ == '__main__':
if (len(sys.argv) != 2):
print USAGE
else:
password = getpass.getpass()
checkSubmissions(sys.argv[1], password)