python获取东京奥运会金牌排行榜及获奖人员并部署云函数每天邮件发送
# python获取东京奥运会金牌排行榜及获奖人员## 前言
别人的00后,征战奥运会,我的00后,在家睡大觉。
作为编程爱好者,刚刚用 python 写了查询奥运会金牌排行榜,并通过云函数发送邮件,查看每天实时数据的小功能,为奥运会做些力所能及的事,助力奥运,中国加油!
!(https://cdn.jsdelivr.net/gh/oddfar/static/img/20210726125152.png)
## 排行榜代码
央视网官网数据
金牌排行榜:<https://2020.cctv.com/medal_list/>
中国奖牌榜获得者:<https://2020.cctv.com/medal_list/details/index.shtml?spm=0.Pe9yiMu0gzhD.ES3pdHUFxT0w.1&countryid=CHN>
截止到目前(2021年7月26日11:48),东京奥运会比赛第三天,我国金牌6,银牌2,铜牌5,名次第一!
!(https://cdn.jsdelivr.net/gh/oddfar/static/img/20210726125200.png)
!(https://cdn.jsdelivr.net/gh/oddfar/static/img/20210726125205.png)
图中"跳水女子双人3米跳板"项目金牌获得者是:施廷懋/王涵夺
通过央网链接,打开F12,分析发现两个链接获取数据
话不多说,上代码
medals.py
```python
import requests
import json
def getMedalsList(url, replaceTxt):
try:
r = requests.get(url)
r.raise_for_status()
r.encoding = r.apparent_encoding
# 替换多余的内容
data = str.replace(r.text, replaceTxt + "(", "")
data = str.replace(data, ");", "")
# 解码json,转成字典
medals = json.loads(data)
return medals
except:
return "Failed!"
# 获取排行榜数据
def getRanking():
url = "https://api.cntv.cn/olympic/getOlyMedals?serviceId=pcocean&itemcode=GEN-------------------------------&t=jsonp&cb=omedals1"
medals = getMedalsList(url, "omedals1")
# 获取数据列表
medalList = medals['data']['medalsList']
res = ""
for i in range(5):
res += "第" + medalList["rank"] + "名:" + medalList["countryname"] + "(" + medalList["countryid"] + ")\n"
res += "金牌/银牌/铜牌:" + medalList["gold"] + "/" + medalList["silver"] + "/" + medalList["bronze"] + "\n\n"
return res
# 中国奖牌获得者数据
def getWinners():
url = "https://api.cntv.cn/Olympic/getOlyMedalList?t=jsonp&cb=OM&serviceId=pcocean&countryid=CHN"
owners = getMedalsList(url, "OM")
# 获取数据列表
ownerList = owners['data']['medalList']
gold = ""# 金牌
silver = ""# 银牌
bronze = ""# 铜牌
for owner in ownerList:
medaltype = owner['medaltype']# 奖牌类型
startdatecn = owner['startdatecn']# 日期CN
item = owner['itemcodename'] + " " + owner['subitemname']# 项目
playname = owner['playname']# 运动员
if medaltype == "ME_GOLD":
gold += "日期:" + startdatecn + "\n项目:" + item + "\n获得者:" + playname+"\n\n"
elif medaltype == "ME_SILVER":
silver += "日期:" + startdatecn + "\n项目:" + item + "\n获得者:" + playname+"\n\n"
elif medaltype == "ME_BRONZE":
bronze += "日期:" + startdatecn + "\n项目:" + item + "\n获得者:" + playname+"\n\n"
res = "\n-------金牌:---------\n" + gold+"\n-------银牌:---------\n" + silver+"\n-------铜牌:---------\n"+ bronze
return res
if __name__ == '__main__':
print(getRanking())
print(getWinners())
```
输出结果:
!(https://cdn.jsdelivr.net/gh/oddfar/static/img/20210726125211.png)
## 发送邮件代码
mail.py
```python
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from medals import getWinners, getRanking
def sendmail():
sender = '*****@qq.com'# 发送邮箱
senderName = "致远"# 发送者昵称
password = '*****'# 发送方QQ邮箱授权码
receivers = ['*****@qq.com',"*****@qq.com"]# 接收邮件
# 三个参数:第一个为文本内容,第二个 plain 设置文本格式,第三个 utf-8 设置编码
str = getRanking() + getWinners()
message = MIMEText(str, 'plain', 'utf-8')
message['From'] = Header(senderName, 'utf-8')# 发送者昵称
# 主题
subject = '东京奥运会金牌排行榜及获奖人员'
message['Subject'] = Header(subject, 'utf-8')
try:
client = smtplib.SMTP_SSL('smtp.qq.com', smtplib.SMTP_SSL_PORT)
print("连接到邮件服务器成功")
client.login(sender, password)
print("登录成功")
client.sendmail(sender, receivers, message.as_string())
print("邮件发送成功")
except smtplib.SMTPException:
print("Error: 无法发送邮件")
if __name__ == '__main__':
sendmail()
```
## 部署云函数方法
登录阿里云,找到函数计算 FC :<https://fc.console.aliyun.com/>
1、创建服务及函数,选择python环境
2、上传两个代码文件,medals.py 和 mail.py
3、编辑 index.py
```python
# -*- coding: utf-8 -*-
import logging
from mail import sendmail
# To enable the initializer feature (https://help.aliyun.com/document_detail/158208.html)
# please implement the initializer function as below:
# def initializer(context):
# logger = logging.getLogger()
# logger.info('initializing')
def handler(event, context):
sendmail()
```
在 “触发器” 中可选择定时触发器,具体操作可查看官方文档 我觉得最好的学习方法就是自己先按照自己的想法写代码,然后和楼主的对比,这样就能发现差距,然后有针对性地提升。看到题干,自己先做题,再对答案,嘿嘿 酷,支持一个 顶顶顶,这个好,支持楼主 666,与时俱进 不错不错,这个很好。 学习的路上,不知道多久能达到这个水平
小伙子真帅, 速度真快{:1_921:} 科技回报社会,你已经很厉害了!能够运用于当前实际问题!
酷,支持一个