Last active
August 11, 2022 05:57
-
-
Save ImSingee/e08166aaa08d2c658738156ea88b2880 to your computer and use it in GitHub Desktop.
LeetCode id -> title slug
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/opt/bin/python3 | |
import os | |
import requests | |
question_id = os.environ.get('KMVAR_LeetCodeID', 'add-two-numbers').strip() | |
cookies={ | |
"LEETCODE_SESSION": '' | |
} | |
def get_csrf_cookie() -> str: | |
response = requests.get( | |
"https://leetcode.com/", | |
cookies=cookies, | |
) | |
return response.cookies["csrftoken"] | |
HEADERS = { | |
'x-csrftoken': get_csrf_cookie(), | |
} | |
def leetcode_id_to_slug(num_id: int): | |
query = '''query problemsetQuestionList($categorySlug: String, $limit: Int, $skip: Int, $filters: QuestionListFilterInput) { | |
problemsetQuestionList( | |
categorySlug: $categorySlug | |
limit: $limit | |
skip: $skip | |
filters: $filters | |
) { | |
hasMore | |
total | |
questions { | |
acRate | |
difficulty | |
freqBar | |
frontendQuestionId | |
isFavor | |
paidOnly | |
solutionNum | |
status | |
title | |
titleCn | |
titleSlug | |
topicTags { | |
name | |
nameTranslated | |
id | |
slug | |
} | |
extra { | |
hasVideoSolution | |
topCompanyTags { | |
imgUrl | |
slug | |
numSubscribed | |
} | |
} | |
} | |
} | |
}''' | |
request_body = { | |
'query': query, | |
'variables': { | |
'categorySlug': '', | |
'filters': { | |
'searchKeywords': '{}.'.format(num_id) | |
}, | |
} | |
} | |
response = requests.post('https://leetcode-cn.com/graphql/', headers=HEADERS, cookies=cookies, json=request_body) | |
questions = response.json()['data']['problemsetQuestionList']['questions'] | |
for question in questions: | |
if str(question['frontendQuestionId']) == str(num_id): | |
return question['titleSlug'] | |
return questions[0]['titleSlug'] | |
if question_id.isnumeric(): | |
question_id = leetcode_id_to_slug(int(question_id)) | |
print(question_id) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment