每天自动给自己发天气预报的脚本
生活随笔
收集整理的這篇文章主要介紹了
每天自动给自己发天气预报的脚本
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
需求:
每天早上起來可以看看天氣預報,然后順便當個鬧鐘使
思路是這樣的:
模塊一:采用yahoo weather api獲取北京的天氣
模塊二:通過網(wǎng)頁版飛信,模擬飛信登陸,給自己發(fā)短信
模塊三:發(fā)送信息
?
一。get_yahoo_weather.py
#!/usr/bin/env python #coding=utf-8 import urllib2 from xml.etree import cElementTree as ET class GetWeather:def __init__(self):self.weather = self.makexml()def makexml(self):url = "http://weather.yahooapis.com/forecastrss?w=2151330&u=c"res = urllib2.urlopen(url)xmlfile = open("yahoo.xml",'w')xmlfile.writelines(res.read())xmlfile.close()return self.xmlET()def xmlET(self):tree = ET.ElementTree(file="yahoo.xml")forecast = []for elem in tree.iter(tag="{http://xml.weather.yahoo.com/ns/rss/1.0}forecast"):forecast.append(elem.attrib)return self.msg(forecast)def msg(self,forecast):msg_data = ""fmt = "\n%s %s %s %s\n"%("日期","天氣","最高溫","最低溫")msg_data += fmtfor i in forecast:msg_data += "%s %s %s %s"%(i['date'],i['text'],i['high'],i['low'])msg_data +="\n"return msg_dataif __name__ == "__main__":w = GetWeather()print w.weather二。fetionsimu.py
#!/usr/bin/env python #coding=utf-8import cookielib import urllib import urllib2 import json import re import timedef fetion(weather_msg = "no data"):cj = cookielib.LWPCookieJar()opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))urllib2.install_opener(opener)t = time.localtime()print t.tm_year,t.tm_mon,t.tm_mdayprint "logining"urlbase = "http://f.10086.cn/im5/" response_text = urllib2.urlopen(urlbase)response_text = response_text.read()partten = re.compile(r'login/login\.action\?mnative=\d&t=\d+')urlplus = partten.search(response_text)urlcomplete = urlbase + urlplus.group(0) # print urlcompleteqheader = {'Referer':urlcomplete}args = {'m':'your phone number','pass':'your password'}logurl = "http://f.10086.cn/im5/login/loginHtml5.action"req = urllib2.Request(logurl,urllib.urlencode(args),qheader)jump = opener.open(req)page = jump.read() # print pagepage = json.loads(page)if page['nickname'] == "LGY":print "login successfully"else:print "error in pass or username"sendmsgurl = "http://f.10086.cn/im5/chat/sendNewGroupShortMsg.action"msg_data = {"touserid":page["idUser"],"msg":weather_msg}msg_back = urllib2.Request(sendmsgurl,urllib.urlencode(msg_data),qheader)msg_jump = opener.open(msg_back)msguse = msg_jump.read()msguse = json.loads(msguse)if msguse["info"] == u"發(fā)送成功":print "send successfully"else:print msguseprint "send failed" if __name__ == "__main__":fetion()三。sendweather.py
#!/usr/bin/env pythonimport time from get_yahoo_weather import GetWeather from fetionsimu import fetion def sendmsg(w):fetion(w)if __name__ == "__main__":w = GetWeather()sendmsg(w.weather)?
最后加入開機啟動
用crontab -e編輯開機啟動項
0 7 * * * /test/mkfun/sendweather.py > /test/mkfun/sdwthmsg.log 2>&1然后就ok了。。。
轉(zhuǎn)載于:https://www.cnblogs.com/lgy6534588/p/3459120.html
總結(jié)
以上是生活随笔為你收集整理的每天自动给自己发天气预报的脚本的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 怎样才能知道自己输卵管通不通畅呢?
- 下一篇: 请不要对我说“你要马上把这个小问题修改好