-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrawler.py
461 lines (394 loc) Β· 16.8 KB
/
crawler.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
from datetime import datetime
import json
import os.path
import pickle
import re
from sys import exit
import time
import requests
from requests.cookies import RequestsCookieJar
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
# from selenium.webdriver.support import expected_conditions as EC
from database import Problem, ProblemTag, Tag, Submission, FavouriteQuestionList
from utils import destructure, random_wait, do, get
COOKIE_PATH = "./cookies.dat"
GRAPHQL_URL = "https://leetcode.com/graphql"
class LeetCodeCrawler:
def __init__(self):
# create an http session
self.session = requests.Session()
self.browser = webdriver.Chrome(service=webdriver.ChromeService(executable_path="./driver/chromedriver"))
self.session.headers.update(
{
'Host': 'leetcode.com',
'Cache-Control': 'max-age=0',
'Upgrade-Insecure-Requests': '1',
'Referer': 'https://leetcode.com/accounts/login/',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6',
'Connection': 'keep-alive'
}
)
def login(self):
browser_cookies = {}
if os.path.isfile(COOKIE_PATH):
with open(COOKIE_PATH, 'rb') as f:
browser_cookies = pickle.load(f)
else:
print("π Starting browser login..., please fill the login form")
try:
# browser login
login_url = "https://leetcode.com/accounts/login"
self.browser.get(login_url)
WebDriverWait(self.browser, 24 * 60 * 3600).until(
lambda driver: driver.current_url.find("login") < 0
)
# Wait for user to complete 2FA manually
time.sleep(10)
browser_cookies = self.browser.get_cookies()
with open(COOKIE_PATH, 'wb') as f:
pickle.dump(browser_cookies, f)
print("π Login successfully")
except Exception as e:
print(f"π€ Login Failed: {e}, please try again")
exit()
cookies = RequestsCookieJar()
for item in browser_cookies:
cookies.set(item['name'], item['value'])
if item['name'] == 'csrftoken':
self.session.headers.update({
"x-csrftoken": item['value']
})
self.session.cookies.update(cookies)
def fetch_favourite_list(self, favorite_slug, skip = 0, limit = 200):
print(f"π€ Fetching problems from Favourite List: https://leetcode.com/problem/{favorite_slug}/...")
query = '''
query favoriteQuestionList(
$favoriteSlug: String!,
$filter: FavoriteQuestionFilterInput,
$filtersV2: QuestionFilterInput,
$searchKeyword: String,
$sortBy: QuestionSortByInput,
$limit: Int,
$skip: Int,
$version: String = "v2"
) {
favoriteQuestionList(
favoriteSlug: $favoriteSlug
filter: $filter
filtersV2: $filtersV2
searchKeyword: $searchKeyword
sortBy: $sortBy
limit: $limit
skip: $skip
version: $version
) {
questions {
id
title
titleSlug
difficulty
status
acRate
topicTags {
name
slug
}
}
totalLength
hasMore
}
}
'''
variables = {
"favoriteSlug": favorite_slug,
"limit": limit,
"skip": skip,
"filtersV2": {
"filterCombineType": "ALL",
"statusFilter": {"questionStatuses": [], "operator": "IS"},
"difficultyFilter": {"difficulties": [], "operator": "IS"},
"topicFilter": {"topicSlugs": [], "operator": "IS"}
},
"sortBy": {"sortField": "CUSTOM", "sortOrder": "ASCENDING"},
"searchKeyword": ""
}
query_params = {
"operationName": "favoriteQuestionList",
"variables": variables,
"query": query,
}
res = self.fetch(query_params)
# parse data
questions = get(res, 'data.favoriteQuestionList.questions')
for question in questions:
FavouriteQuestionList.replace(
slug=question['titleSlug'],
status=question['status'],
title=question['title'],
).execute()
print(f"π€ Number of Favourite {len(questions)} problems")
return questions
def fetch_favourite_problems(self):
response = self.session.get("https://leetcode.com/api/problems/all/")
all_problems = json.loads(response.content.decode('utf-8'))
# filter AC problems
counter = 0
for item in all_problems['stat_status_pairs']:
id, slug = destructure(item['stat'], "question_id", "question__title_slug")
if FavouriteQuestionList.get_or_none(FavouriteQuestionList.slug == slug):
# only update problem if not exists
if Problem.get_or_none(Problem.id == id) is None:
counter += 1
# fetch problem
do(self.fetch_problem, args=[slug, True])
# fetch solution
do(self.fetch_solution, args=[slug])
# always try to update submission
do(self.fetch_submission, args=[slug])
print(f"π€ Updated {counter} problems")
def fetch_accepted_problems(self):
response = self.session.get("https://leetcode.com/api/problems/all/")
all_problems = json.loads(response.content.decode('utf-8'))
# filter AC problems
counter = 0
for item in all_problems['stat_status_pairs']:
if item['status'] == 'ac':
id, slug = destructure(item['stat'], "question_id", "question__title_slug")
# only update problem if not exists
if Problem.get_or_none(Problem.id == id) is None:
counter += 1
# fetch problem
do(self.fetch_problem, args=[slug, True])
# fetch solution
do(self.fetch_solution, args=[slug])
# always try to update submission
do(self.fetch_submission, args=[slug])
print(f"π€ Updated {counter} problems")
def fetch_problem(self, slug: str, accepted: bool=False) -> None:
print(f"π€ Fetching problem: https://leetcode.com/problem/{slug}/...")
query_params = {
'operationName': "getQuestionDetail",
'variables': {'titleSlug': slug},
'query': '''query getQuestionDetail($titleSlug: String!) {
question(titleSlug: $titleSlug) {
questionId
questionFrontendId
questionTitle
questionTitleSlug
content
difficulty
stats
similarQuestions
categoryTitle
topicTags {
name
slug
}
}
}'''
}
res = self.fetch(query_params)
# parse data
question = get(res, 'data.question')
Problem.replace(
id=question['questionId'],
display_id=question['questionFrontendId'],
title=question["questionTitle"],
level=question["difficulty"],
slug=slug,
description=question['content'],
accepted=accepted,
approaches='',
mistakes='',
edgecases='',
clarify_questions='',
note='',
).execute()
for item in question['topicTags']:
if Tag.get_or_none(Tag.slug == item['slug']) is None:
Tag.replace(
name=item['name'],
slug=item['slug']
).execute()
ProblemTag.replace(
problem=question['questionId'],
tag=item['slug']
).execute()
random_wait(10, 15)
def fetch_solution(self, slug: str) -> None:
print(f"π€ Fetching solution for problem: {slug}")
query_params = {
"operationName": "QuestionNote",
"variables": {"titleSlug": slug},
"query": '''
query QuestionNote($titleSlug: String!) {
question(titleSlug: $titleSlug) {
questionId
article
note
solution {
id
content
contentTypeId
canSeeDetail
paidOnly
rating {
id
count
average
userRating {
score
__typename
}
__typename
}
__typename
}
__typename
}
}
'''
}
res = self.fetch(query_params)
# parse data
solution = get(res, "data.question")
is_solution_existed = solution['solution'] is not None and solution['solution']['paidOnly'] is False
if is_solution_existed:
data = self.decompose_note(solution['note'])
Problem.update({
Problem.approaches:data['approaches'],
Problem.mistakes:data['mistakes'],
Problem.edgecases:data['edgecases'],
Problem.clarify_questions:data['clarify_questions'],
Problem.note:data['note'],
}).where(Problem.slug == slug).execute()
# Solution.replace(
# problem=solution['questionId'],
# url=f"https://leetcode.com/articles/{slug}/",
# content=solution['solution']['content']
# ).execute()
random_wait(10, 15)
def decompose_note(self, input_str: str) -> dict:
"""
Extracts sections (clarify questions, edgecases, approaches, mistakes, note) from the input string.
:param input_str: The input string with section headers and content.
:return: Dictionary with extracted content for each section.
"""
# Improved regex pattern to capture content between section headers
pattern = re.compile(
r"clarify questions:\s*(?P<clarify>(?:- .*(?:\n|$))*)" # Clarify Questions
r"(?:\nedgecases:\s*(?P<edgecase>(?:- .*(?:\n|$))*)?)?" # Edgecases (optional)
r"(?:\napproaches:\s*(?P<approach>(?:- .*(?:\n|$))*)?)?" # Approaches (optional)
r"(?:\nmistakes:\s*(?P<mistake>(?:- .*(?:\n|$))*)?)?" # Mistakes (optional)
r"(?:\nnote:\s*(?P<note>.*))?", # Note (optional)
re.IGNORECASE
)
match = pattern.search(input_str)
if not match:
print("β Personal not could not be found.")
return {section: "None" for section in ["clarify_questions", "edgecases", "approaches", "mistakes", "note"]}
def format_title(key: str) -> str:
"""Converts keys like 'clarify_questions' to 'Clarify Questions'."""
return key.replace("_", " ").title()
def format_section(title: str, text: str, is_bullet_section: bool = True) -> str:
"""
Formats a section into a human-readable string.
:param title: Section title.
:param text: Section content.
:param is_bullet_section: True if the section contains bullet points; False otherwise.
:return: Formatted section string.
"""
if not text:
return f"{title}:\n - None" if is_bullet_section else f"{title}:\nNone"
lines = [line.strip('- ').strip() for line in text.strip().split('\n') if line.strip()]
if is_bullet_section:
return f"{title}:\n" + "\n".join(f" - {line}" for line in lines)
else:
return f"{title}:\n{lines[0]}" # For single-line content like 'note'
# Extract, clean, and format sections
sections = {
"clarify_questions": format_section(format_title("πΉ clarify_questions"), match.group('clarify')),
"edgecases": format_section(format_title("πΉ edge_cases"), match.group('edgecase')),
"approaches": format_section(format_title("πΉ approaches"), match.group('approach'), is_bullet_section=False),
"mistakes": format_section(format_title("πΉ mistakes"), match.group('mistake')),
"note": format_section(format_title("πΉ note"), match.group('note'), is_bullet_section=False),
}
return sections
def fetch_submission(self, slug: str) -> None:
print(f"π Fetching submission for problem: {slug}")
query_params = {
'operationName': "Submissions",
'variables': {
"offset": 0,
"limit": 20,
"lastKey": '',
"questionSlug": slug
},
'query': '''query Submissions($offset: Int!, $limit: Int!, $lastKey: String, $questionSlug: String!) {
submissionList(offset: $offset, limit: $limit, lastKey: $lastKey, questionSlug: $questionSlug) {
lastKey
hasNext
submissions {
id
statusDisplay
lang
runtime
timestamp
url
isPending
__typename
}
__typename
}
}'''
}
res = self.fetch(query_params)
# parse data
submissions = get(res, "data.submissionList.submissions")
if len(submissions) > 0:
for sub in submissions:
if Submission.get_or_none(Submission.id == sub['id']) is not None:
continue
if sub['statusDisplay'] == 'Accepted':
id = sub['id']
code = self.fetch_submission_details(id)
if code:
Submission.insert(
id=sub['id'],
slug=slug,
language=sub['lang'],
submitted_date=datetime.fromtimestamp(int(sub['timestamp'])),
source=code
).execute()
else:
raise Exception(f"Cannot get submission code for problem: {slug}")
print(f"β
Successfully saved accepted submission for: {slug}")
break # Stop after saving the first accepted submission
random_wait(10, 15)
def fetch_submission_details(self, submission_id):
print(f"π Fetching submission details code for problem: {submission_id}")
query_params = {
'operationName': "submissionDetails",
'variables': {
"submissionId": submission_id,
},
'query': '''query submissionDetails($submissionId: Int!) {
submissionDetails(submissionId: $submissionId) {
code
timestamp
}
}'''
}
res = self.fetch(query_params)
return get(res, "data.submissionDetails.code")
def fetch(self, query_params):
response = self.session.post(
GRAPHQL_URL,
data=json.dumps(query_params).encode('utf8'),
headers={"content-type": "application/json"},
)
return json.loads(response.content)