版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhaoenweiex/article/details/82563887
前言
一直比较关心各大经济指数的走向,但是发现很多这方面的消息都是需要打开指定网页或app才能知道的,没有找到提供主动推送数据的服务。于是就想结合python自己动手搞一个,正好用来练手,很快就搞定了,本来计划使用短信推送的但发现短信管制很严,还是用邮箱凑合一下吧。
主要作用
对感兴趣的指数进行收集,并通过短信在指定时间发送到指定邮箱中
主要依赖的服务
1.全球经济指数接口
https://www.nowapi.com/api/finance.globalindex
这个api需要自己去nowapi申请对应的appkey和sgin
2.邮箱的STMP服务。需要配置STMP地址以及用户名密码。
使用方法
将个人信息写入config.json中,执行脚本即可
源码如下
python脚本
#!/usr/bin/python3
# _*_ coding: utf-8 _*_
import requests
import json
import time
import datetime
import smtplib
#发送字符串的邮件
from email.mime.text import MIMEText
def getRealtimeInfo(indexId):
url = "http://api.k780.com/?app=finance.globalindex&inxno="+indexId + \
"&appkey=36516&sign=28ec390cd147af00af32884b1723aef4&format=json"
res = requests.get(url)
result = res.text
return result
def loadConfig():
configFile = open('config.json', 'r',encoding='utf-8')
configJson = json.load(configFile)
configFile.close()
return configJson
def sendMail(fromaddr,toaddr,psw,serverAddress,topic,content):
server = smtplib.SMTP(serverAddress)
server.login(fromaddr,psw)
m = MIMEText(content, 'plain', 'utf-8') # 内容, 格式, 编码
m['From'] = "{}".format(fromaddr)
m['To'] = toaddr
m['Subject'] = topic
server.sendmail(fromaddr, toaddr, m.as_string())
print('send success')
server.quit()
def sendUpdatedInfo():
for userInfo in userInfos:
sms_content = ''
for indexInfo in userInfo["indexs"]:
name = indexInfo["name"]
indexId = indexInfo["id"]
indexRealtimeInfo = getRealtimeInfo(indexId)
text = name+"浮动" + \
json.loads(indexRealtimeInfo)['result']['change_price_per']
print(text)
sms_content = sms_content+text+";"
sendMail(emailaddress, userInfo["mail"],
password, smtp_server, "指数更新", sms_content)
if __name__ == '__main__':
emailaddress = '[email protected]'
# 注意使用开通POP,SMTP等的授权码
password = '*'
smtp_server = 'smtp.163.com'
userInfos = loadConfig()
while True:
# 判断是否达到设定时间,例如0:00
while True:
now = datetime.datetime.now()
print("定时检测"+str(now))
# 到达设定时间,结束内循环
if now.hour == 23 and now.minute == 00:
break
# 不到时间就等60秒之后再次检测
time.sleep(60)
print("到点触发更新信息")
sendUpdatedInfo()
config.json
[
{
"mail": "[email protected]",
"indexs": [
{
"name": "沪深300",
"id": "000300"
},
{
"name": "道琼斯",
"id": "INDU"
},
{
"name": "标普500",
"id": "SPX"
},
{
"name": "纳斯达克",
"id": "CCMP"
}
]
}
]