使用python实现了一个力扣每日一题每天自动邮件提醒的小爬虫,小但实用!!!
需求来源于生活,对于只是偶尔有兴趣做做题的我,力扣的每日一题对我一直有以下的不便:
其实有些需求主要是因为我懒(bushi),但是,程序员要学会偷懒!于是我简单整理了一下我的需求:
说干就干,开工!于是花了一点时间把这样一个小玩意儿弄出来了。
其实这件事情很简单,我只需要分析出力扣上每日一题的接口,然后写个python脚本把题目信息拿到,然后用smtp协议给我自己发封邮件即可,将这个脚本写入我服务器的crontab上,每天早上就自己跑了。接下来按照这些部分去分析即可。
大致就是:分析接口协议->获取题目信息->写脚本将信息发送到我的邮箱->将这个接口写入crontab。
开始之前先讲点武德,我们先看一下力扣的robots.txt,看看哪些是不能爬的:
然后再去抓个包,看下哪个包最后得到了每日一题的数据:
发现这个包请求的结果就是每日一题:
幸运的是,这个接口并没有在上述robots.txt中,我们可以写个脚本模拟一下这个发包,注意到请求头中有csrf-token:
稍微找一下,可以发现返回包的COOKIE里面就带有csrf-token,所以我们提前请求一下即可,就可以从COOKIE中拿到csrf-token了。
这个请求体,很明显是graphql的请求参数,仔细看一下,发现并不需要传啥参数,所以直接调用即可。
再去看一下进入题目页面时候的关键请求接口,可以找到是这个接口:
返回的数据都是json,格式化一下就可以找到关键数据。
此篇若有不清楚的见下面使用说明
每天上午11点自动提醒:(替换成自己的路径)
crontab –e
0 11 * * * python3 /home/atfwus/sheduler-script/lc-today-question/lc-day-title.py
D.成品
lc-day-title.py,自动采集每日一题的数据并发邮件提醒:
import requests,json,time
session = requests.session()
lc_url = 'https://leetcode.cn'
graphql_url = '/graphql'
def int_csrf():
session.get(lc_url + graphql_url)
int_csrf()
user_agent = r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'
headers = {
'x-requested-with' : 'XMLHttpRequest',
'accept' : '*/*',
'User-Agent': user_agent,
'Connection': 'keep-alive',
'origin': 'https://leetcode.cn',
'Content-Type' :'application/json',
'X-Csrftoken': session.COOKIEs['csrftoken']
}
def get_today_question():
param = '''
query questionOfToday {
todayRecord {
date
userStatus
question {
questionId
frontendQuestionId: questionFrontendId
difficulty
title
titleCn: translatedTitle
titleSlug
paidOnly: isPaidOnly
freqBar
isFavor
acRate
status
solutionNum
hasVideoSolution
topicTags {
name
nameTranslated: translatedName
id
}
extra {
topCompanyTags {
imgUrl
slug
numSubscribed
}
}
}
lastSubmission {
id
}
}
}
'''
data = {
"query": param,
"variables": {}
}
r = session.post(lc_url+graphql_url, headers=headers, data=json.dumps(data))
return r.json()
def get_one_question(title_slug):
param = '''
query questionData($titleSlug: String!) {
question(titleSlug: $titleSlug) {
questionId
questionFrontendId
categoryTitle
boundTopicId
title
titleSlug
content
translatedTitle
translatedContent
isPaidOnly
difficulty
likes
dislikes
isLiked
similarQuestions
contributors {
username
profileUrl
avatarUrl
__typename
}
langToValidPlayground
topicTags {
name
slug
translatedName
__typename
}
companyTagStats
codeSnippets {
lang
langSlug
code
__typename
}
stats
hints
solution {
id
canSeeDetail
__typename
}
status
sampleTestCase
metaData
judgerAvailable
judgeType
mysqlSchemas
enableRunCode
envInfo
book {
id
bookName
pressName
source
shortDescription
fullDescription
bookImgUrl
pressImgUrl
productUrl
__typename
}
isSubscribed
isDailyQuestion
dailyRecordStatus
editorType
ugcQuestionId
style
exampleTestcases
jsonExampleTestcases
__typename
}
}
'''
data = {
"operationName": "questionData",
"variables": {
"titleSlug": title_slug
},
"query": param
}
r = session.post(lc_url + graphql_url, headers=headers, data=json.dumps(data))
return r.json()
def send_to_mail(q, sf):
q = q['data']['question']
id = q['questionFrontendId']
title = q['translatedTitle']
url = 'https://leetcode.cn/problems/' + q['titleSlug']
ac_rate = '{:.2%}'.format(sf['acRate'])
def generate_subject():
day_str = time.strftime('%m月%#d日', time.localtime(time.time()))
return f'力扣{day_str}每日一题来咯!!!({id}.{title})'
print(generate_subject())
def generate_plain():
content = q['translatedContent']
difficulty = q['difficulty']
tags = []
for i in q['topicTags']:
tags.append(i['translatedName'])
tags_str = ' '.join(tags)
return f'''
题目名称&#xff1a;{id}.{title}     题目难度&#xff1a;<strong>{difficulty}</strong>     AC率&#xff1a;{ac_rate}     题目链接&#xff1a;<a href&#61;"{url}">{url}</a><br>
题目标签&#xff1a;{tags_str}<br>
{content}
&#39;&#39;&#39;.strip()
print(generate_plain())
from mail import send_mail
send_mail(subject&#61;generate_subject(), plain&#61;generate_plain())
sf &#61; get_today_question()
s &#61; get_one_question(sf[&#39;data&#39;][&#39;todayRecord&#39;][0][&#39;question&#39;][&#39;titleSlug&#39;])
send_to_mail(s, sf[&#39;data&#39;][&#39;todayRecord&#39;][0][&#39;question&#39;])
mail.py&#xff0c;用于发邮件&#xff1a;
import smtplib
from email.mime.text import MIMEText
from email.header import Header
def init_con():
# 创建 SMTP 对象
smtp &#61; smtplib.SMTP()
# 连接&#xff08;connect&#xff09;指定服务器
smtp.connect("smtp.qq.com", port&#61;25)
# 登录&#xff0c;需要&#xff1a;登录邮箱和授权码
smtp.login(user&#61;"***", password&#61;"***")
return smtp
def send_mail(subject, plain):
smtp &#61; init_con()
# 构造MIMEText对象&#xff0c;参数为&#xff1a;正文&#xff0c;MIME的subtype&#xff0c;编码方式
message &#61; MIMEText(plain, &#39;html&#39;, &#39;utf-8&#39;)
message[&#39;From&#39;] &#61; Header("Leetcode 每日一题提醒 By ATFWUS", &#39;utf-8&#39;) # 发件人的昵称
message[&#39;To&#39;] &#61; Header("ATFWUS", &#39;utf-8&#39;) # 收件人的昵称
message[&#39;Subject&#39;] &#61; Header(subject, &#39;utf-8&#39;) # 定义主题内容
smtp.sendmail(from_addr&#61;"***", to_addrs&#61;"***", msg&#61;message.as_string())
每日一题来咯&#xff01;&#xff01;&#xff01;
只需要修改mail.py中的邮箱和密码即可&#xff0c;然后将两个py文件放在云服务器上&#xff0c;crontab定时任务自动执行。
下面是密码的获取方式&#xff1a;
qq邮箱中&#xff0c;点设置&#xff0c;在这个地方找到授权码&#xff0c;申请授权码&#xff0c;并填在上面mail.py脚本的password上。
本文仅供技术交流学习使用&#xff0c;严禁使用于任何商业用途&#xff0c;若有任何侵权行为请联系我删除&#xff01;
ATFWUS 2022-12-05