Leetcode题目更新提醒小脚本~

本文介绍了一个用Python编写的脚本,用于检查LeetCode是否有新的可解题目,并在发现新题时通过邮件通知用户。脚本依赖于BeautifulSoup库进行网页解析,需要将其部署到云主机上,如实验室服务器。为了防止ssh断开导致进程结束,使用了nohup命令确保脚本持续运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Leetcode缺少一个 出现新题目就发邮件提醒用户的功能,所以写了一个脚本。

脚本有两个函数:检查leet网站是否有新题目,并且题目是能做的、没加锁的;发邮件提醒用户。

网站解析用的是beautifulSoup 所以需要预先安装bs4模块

脚本写完需要上传到云主机上,这里简单起见 我用的是实验室的服务器,上传并运行该脚本。

这里有个小问题要解决,ssh运行python断开终端后会杀死该进程,要用nohup python xxx.py & 命令保证该进程不被杀死 一直保持运行。

#!/usr/bin/env
#coding:utf-8
import urllib,re,time
import smtplib  
from email.mime.text import MIMEText  
from email.header import Header  
from bs4 import BeautifulSoup

def checkUpdate(latest):
	url = "https://leetcode.com/problemset/algorithms/" #网页地址
	wp = urllib.urlopen(url) #打开连接
	soup = BeautifulSoup(wp.read())
	count=0
	lock,update = False,False
	for link in soup.find_all('tr'):
		count=count+1
	#print(link)
		if count==3:
			for tds in link.find_all('td'):
				if(tds.string==str(latest)):
					update = True
				if(tds.find('i')!=None):
					lock = True
			break

	if update and not lock:
		print "We will send an email to inform users that a new question has arised."
		return 0
	elif update and lock:
		return 1
	else:
		return 2


def sendMails(recvlist):
	sender = '13760274091@163.com'  
	subject = 'leetcode又有新题目可以做了'  
	smtpserver = 'smtp.163.com'  
	username = '13760274091@163.com'  
	password = 'xxxxx'  
  
	msg = MIMEText('<html><h2>leetcode有新题目啦~~ <a href="https://leetcode.com/problemset/algorithms/">题目链接</a></h2></html>','html','utf-8')#中文需参数‘utf-8',单字节字符不需要  
	msg['Subject'] = Header(subject, 'utf-8')  
	msg['From'] = '13760274091@163.com'    
	#msg['To'] = "zhushuai2015@qq.com"  
	smtp = smtplib.SMTP()  
	smtp.connect('smtp.163.com')  
	smtp.login(username, password)  
	for receiver in recvlist:
		msg['To']=receiver
		smtp.sendmail(sender, receiver, msg.as_string())  
	smtp.quit() 

if __name__ == '__main__':
	latest = 377
	recvs =['zhushuai2015@qq.com','xxxxx@qq.com'];
	while  True:
		state = checkUpdate(latest)
		if(state==0):#有新题且无锁
			latest = latest+1
			sendMails(recvs)
		elif(state==1):#有新题但有锁
			latest=latest+1
		time.sleep(60)#1m检查一次


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值