-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfetch-leetcode.py
executable file
·117 lines (92 loc) · 2.54 KB
/
fetch-leetcode.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
#!/usr/bin/env python3
# coding=utf-8
import argparse
import http.client
import json
import os
import urllib.parse
__author__ = "Jie Liu <eirture@gmail.com>"
LEETCODE_URL = "https://leetcode.cn/graphql/"
CONTENT_GRAPHQL = '''query questionData($titleSlug: String!) {
question(titleSlug: $titleSlug) {
questionId
questionFrontendId
boundTopicId
title
titleSlug
content
translatedTitle
translatedContent
isPaidOnly
difficulty
similarQuestions
topicTags {
name
slug
translatedName
__typename
}
status
sampleTestCase
exampleTestcases
__typename
}
}'''
template = '''
## Solutions
'''
def get_slug(url):
# type: (str) -> str
slugs = url.split('/')
for i in reversed(slugs):
if i:
return i
return ''
def get_content(url):
slug = get_slug(url)
if not slug:
err("unsupported url {}", url)
data = {
"operationName": "questionData",
"variables": {
"titleSlug": slug
},
"query": CONTENT_GRAPHQL
}
p = urllib.parse.urlparse(LEETCODE_URL)
clazz = http.client.HTTPSConnection if p.scheme == 'https' else http.client.HTTPConnection
conn = clazz(p.hostname, p.port)
conn.request(
"POST", p.path, json.dumps(data),
{'Content-Type': 'application/json', 'origin': 'https://leetcode.cn'}
)
resp = conn.getresponse()
if resp.status // 100 != 2:
err(resp.reason)
return json.loads(resp.read()).get("data", {}).get("question") or {}
def err(fmt, *args):
print("err: {}".format(fmt.format(*args)))
exit(-1)
def write2file(url, output):
data = get_content(url)
if not data:
err("have no content of {}", url)
qid = data.get('questionId')
title = data.get('translatedTitle') or data.get('titleSlug')
content = data.get('translatedContent') or data.get('content')
filename = "{}-{}.md".format(qid, data.get('titleSlug'))
filepath = os.path.join(output, filename)
print(filepath)
with open(filepath, 'w+') as f:
f.write('# [{}. {}]({}) - {}\n\n'.format(qid, title, url, data.get('difficulty', '').lower()))
f.write(content)
f.write('\n')
f.write(template)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("url", help="the url address of leetcode")
parser.add_argument("-o", "--out", default="", help="the output directory path")
args = parser.parse_args()
write2file(args.url, args.out)
if __name__ == '__main__':
main()