用python制作每天定时给你发送天气预报的机器人

绪论

该项目涉及数据爬虫,从网页爬取指定数据,通过设置钉钉机器人每天自动的定时推送明日的天气预报信息。(下述代码可直接运行)

具体实现见如下代码:

from bs4 import BeautifulSoup
#以下包为连接机器人
import requests
import json
url = 'http://www.weather.com.cn/weather/101020100.shtml'
res = requests.get(url)
res.encoding = 'utf-8'
soup = BeautifulSoup(res.text, 'html.parser')
weather_list = soup.find('ul', class_='t clearfix').findAll('li')
tomorrow = weather_list[1] # 获取明天的天气信息
date = tomorrow.find('h1').text # 获取日期
weather = tomorrow.find(class_='wea').text # 获取天气

temp = tomorrow.find('p', class_='tem').findAll('span') # 获取最高和最低温度
high_temp = temp[0].text + '℃' # 最高温度
temp1 = tomorrow.find('p', class_='tem').findAll('i') # 获取最高和最低温度
low_temp = temp1[0].text + '℃' # 最低温度
print('日期:', date)
print('天气:', weather)
print('最高温度:', high_temp)
print('最低温度:', low_temp)

###################
####编辑机器人输出###
###################
def push_report(web_hook):
 # 定时任务触发钉钉报告推送
 key_word = "未解决工单预警"

 header = {
  "Content-Type": "application/json;charset=UTF-8"
 }
 message_body = {
  "msgtype": "markdown",
  "markdown": {
   "title": key_word,
   "text": "# <font color=#FF8C00 size=6 >天气提醒:</font> \n"
           "## **%s**\n" % date +
           "天气为:%s" % weather

  },
  "at": {
   "atMobiles": [],
   "isAtAll": False
  }
 }

 send_data = json.dumps(message_body)  # 将字典类型数据转化为json格式
 ChatBot = requests.post(url=web_hook, data=send_data, headers=header)
 opener = ChatBot.json()
 if opener["errmsg"] == "ok":
  print(u"%s 通知消息发送成功!" % opener)
 else:
  print(u"通知消息发送失败,原因:{}".format(opener))


##########
###输出###
##########
if __name__ == '__main__':
 # webhook 来自于 获取机器人webhook:复制webhook 中的那个值
 webhook = "https://oapi.dingtalk.com/robot/send?access_token=670ba879f957284eba4dbff98829c3f0a33f6e4e3a64be6fc52c01c9b5dea047"
 push_report(webhook)

实现效果展示

具体想让机器人编辑输出更好看一点,可以参照上述的代码,获取更多的信息之后编辑机器人输出。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值