更多教程请移步至:洛凉博客
求助请移步至:Python自学技术交流
一:介绍
本代码在Python3环境下编写,使用(requests,json,time,email)模块,不保证其他环境可用,如果到问题请自行解决或进群求助。
1、反正我手上的iOS里面的自带天气APP刷新太慢,每天早上赶着上班想看看天气都不行,简直急死人。
然后网上搜了一下天气API,很多免费的API,我这里选的是墨迹天气API,免费,一年内可以调用2000次/每个账号。好了,不瞎扯了,直接开撸。
2、由于墨迹天气API是用过地区经纬度查询天气情况,第一个问题就要解决通过实际的地理位置获取到经纬度,大家不用担心,很easy的事,也是直接调用第三方API就行了(这里调用腾讯的API)。
3、本人代码写好直接放在Linux系统通过执行定时任务自动执行。(每天早上7:20通过邮箱发送至指定邮箱)
然后每天早上打开手机邮箱就能很直观的获取到近三日天气情况。
有兴趣的同学可以自行搜索Linux定时任务机制及简单使用方法。
二:通过地理位置获取经纬度
直接贴代码吧,不是很难得事,大家遵循腾讯API传参规范就行了。
不过大家要去注册一个腾讯开发者账号,获取开发者密钥。
传送门:腾讯位置服务
以下代码文件名命名为:loala.py
import requests
import json
from time import sleep
def getlalo():
result = False
while result == False:
address = input('\n请输入您所在的城市(注:地址中请包含城市名称):')
url = 'http://apis.map.qq.com/ws/geocoder/v1/?address={}&key='这里请输入你自己的开发者密钥'.format(
address)
r = requests.get(url=url)
d = json.loads(r.text)
if d.get('message') == 'query ok':
return d.get('result').get('location')
elif address == 'q':
print('\n您已选择退出,感谢您的使用,再见!(五秒后自动关闭)')
sleep(5)
break
elif d.get('message') == '查询无结果':
print('\n您输入的地址有误,请重新输入:')
continue
if __name__ == "__main__":
ll = getlalo()
三:墨迹天气API解析
现在开放的API一般result都是以json形式返回。第一步就是通过上面获取到的经纬度去查询天气,第二步就是解析JSON。
有兴趣的同学可以去阿里云市场搜索天气API,由于免费的API调用一般都要传递key。SO大家还是要注册一个阿里云账号,然后购买墨迹免费天气API,会生成key值。
下面代码中还存在邮箱发送模块,有兴趣的同学可以自己搜索学习,我这里就是调用简单的发送模块。
import requests
import json
from email.mime.text import MIMEText
from email.header import Header
from smtplib import SMTP_SSL
from time import sleep
def getweather(url,lat,lon,appcode):
'''获取近三天天气情况'''
try:
headers = {
'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
'Authorization':'APPCODE '+appcode
}
bodys = {
'lat' : lat,
'lon' : lon,
'token' : '''443847fa1ffd4e69d929807d42c2db1b'''
}
html = requests.post(url,data=bodys,headers=headers)
html.encoding = html.apparent_encoding
html = json.loads(html.text)
weather = html.get('data').get('forecast')
city = str(html.get('data').get('city').get('counname')) + str(html.get('data').get('city').get('pname')) + str(html.get('data').get('city').get('name'))
weathers = []
for a in weather:
ygrq = "预告日期:{}".format(a.get('predictDate'))
btqk = "日间天气情况:{}".format(a.get('conditionDay'))
wsqk = "晚间天气情况:{}".format(a.get('conditionNight'))
zdwd = "当天最低温度:{}度".format(a.get('tempNight'))
zgwd = "当天最高温度:{}度".format(a.get('tempDay'))
btfx = "日间风向:{},级数:{}级".format(a.get("windDirDay"),a.get('windLevelDay'))
wsfx = "晚间风向:{},级数:{}级".format(a.get("windDirNight"), a.get('windLevelNight'))
weathers.append(ygrq)
weathers.append(btqk)
weathers.append(wsqk)
weathers.append(zdwd)
weathers.append(zgwd)
weathers.append(btfx)
weathers.append(wsfx)
return weathers,city
except BaseException as f:
return "获取近三天天气情况失败,错误信息为:{}".format(f)
def sendmail(weathers,receiver):
# qq邮箱smtp服务器
host_server = 'smtp.qq.com'
# sender_qq为发件人的qq号码
sender_qq = '输入发送邮件的邮箱地址'
# pwd为qq邮箱的授权码
pwd = '输入发送邮件的邮箱密码,如果是QQ邮箱传入授权码'
# 发件人的邮箱
sender_qq_mail = '3301885103@qq.com'
# 收件人邮箱
receiver = receiver
hh = ','
try:
# 邮件的正文内容
today = ''
tomorrow = ''
dftomorrow = ''
for a in weathers[0][0:7]:
b = a + hh
today +=b
for a in weathers[0][7:14]:
b = a + hh
tomorrow +=b
for a in weathers[0][14:21]:
b = a + hh
dftomorrow +=b
mail_content = today + '\n\n' + tomorrow + '\n\n' + dftomorrow
# 邮件标题
mail_title = weathers[1] + "近三日天气情况"
# ssl登录
smtp = SMTP_SSL(host_server)
# set_debuglevel()是用来调试的。参数值为1表示开启调试模式,参数值为0关闭调试模式
smtp.set_debuglevel(0)
smtp.ehlo(host_server)
smtp.login(sender_qq, pwd)
msg = MIMEText(mail_content, "plain", 'utf-8')
msg["Subject"] = Header(mail_title, 'utf-8')
msg["From"] = sender_qq_mail
msg["To"] = receiver
print('\n您当前查询的地区近三日天气情况如下:')
print('\n' + mail_content)
smtp.sendmail(sender_qq_mail, receiver, msg.as_string())
smtp.quit()
except:
mail_title = '内容出错了'
mail_content = weathers
# ssl登录
smtp = SMTP_SSL(host_server)
# set_debuglevel()是用来调试的。参数值为1表示开启调试模式,参数值为0关闭调试模式
smtp.set_debuglevel(0)
smtp.ehlo(host_server)
smtp.login(sender_qq, pwd)
msg = MIMEText(mail_content, "plain", 'utf-8')
msg["Subject"] = Header(mail_title, 'utf-8')
msg["From"] = sender_qq_mail
msg["To"] = receiver
smtp.sendmail(sender_qq_mail, receiver, msg.as_string())
smtp.quit()
if __name__ == "__main__":
url = 'http://apifreelat.market.alicloudapi.com/whapi/json/aliweather/briefforecast3days'
appcode = '这里传入自己的阿里云账号key'
# 可在http://api.map.baidu.com/lbsapi/getpoint/index.html手动获取某地经纬度
from loala import getlalo
lat = ll.get('lat') #纬度
lon = ll.get('lng') #经度
weather = getweather(url,lat,lon,appcode)
receiver = input('\n请输入需要接收天气的电子邮箱地址:') #邮件人邮箱地址
sendmail(weather,receiver)
print('\n发送成功,请查收邮箱,谢谢!程序5秒后自动关闭!!')
sleep(5)
四:总结
其实个人使用不用这么复杂,直接使用下面的代码就够用了,直接通过百度地图API服务获取自己长住地经纬度,然后写死在代码里面。
这里用Linux定时任务每天自动运行文件比较方便,然后通过配置的默认邮箱发送至指定邮箱。
有需要的可以进群获取打包好的EXE可执行文件。
网友评论