绪论
该项目涉及数据爬虫,从网页爬取指定数据,通过设置钉钉机器人每天自动的定时推送明日的天气预报信息。(下述代码可直接运行)
具体实现见如下代码:
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)
实现效果展示
具体想让机器人编辑输出更好看一点,可以参照上述的代码,获取更多的信息之后编辑机器人输出。