摘要:本文主要向大家介绍了利用Python语言监控天气,通过具体的内容向大家展示,希望对大家学习Python语言有所帮助。
本文主要向大家介绍了利用Python语言监控天气,通过具体的内容向大家展示,希望对大家学习Python语言有所帮助。
需求:从天气网站抓取天气,在每天6点,检查当天是否会下雨。如果下雨,邮件提醒带伞。代码:[root@pos ~]# cat weather.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import requests,bs4,smtplib
def sendMail(body):
smtp_server = 'smtp.126.com'
from_mail = 'pp_1990@126.com'
mail_pass = 'xxxxxxxxxx'
to_mail = ['50xxxxxx6@qq.com']
from_name = 'Weather Monitor'
subject = 'Raining Today!'
mail = [
"From: %s <%s>" % (from_name, from_mail),
"To: %s" % ','.join(to_mail),
"Subject: %s" % subject,
"",
body
]
msg = '\n'.join(mail)
try:
s = smtplib.SMTP_SSL('smtp.126.com',465)
s.login(from_mail, mail_pass)
s.sendmail(from_mail, to_mail, msg)
s.quit()
except smtplib.SMTPException as e:
print("Error: "+e)
if __name__ == "__main__":
headers={'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0'}
url='//www.tianqi.com/shanghai/'
urlhtml=requests.get(url,headers=headers)
urlhtml.raise_for_status()
weatherhtml=bs4.BeautifulSoup(urlhtml.text[:],'html.parser')
weather=weatherhtml.select('div li p')
for i in range(len(weather)):
weathnow=weather[i].getText()
if weathnow == '有雨':
sendMail("It's rainy today. Remember to bring your umbrella!")
print("DONE!")将脚本写入计划任务,每天6点执行一次。计划任务可以采用Task Scheduler(windows)、launchd(OS X)、cron(linux)等系统工具。当然,也可以采用发送短信的方式进行通知。
本文由职坐标整理并发布,希望对同学们学习Python有所帮助,更多内容请关注职坐标编程语言Python频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号