Python之钉钉机器人推送天气预报
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python之钉钉机器人推送天气预报相关的知识,希望对你有一定的参考价值。
通过Python脚本结合钉钉机器人,定时向钉钉群推送天气预报
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: [email protected]
# My blog http://m51cto.51cto.blog.com
import requests
import re
import urllib2
import json
import sys
import os
headers = {‘Content-Type‘: ‘application/json;charset=utf-8‘}
api_url = "https://oapi.dingtalk.com/robot/send?access_token=37e23308d1b84eb4ac34566e03c4c4e74bxxx7xxxxxxxxxxx"
##从钉钉机器人设置中拷贝
def msg(text):
json_text= {
"msgtype": "text",
"at": {
"atMobiles": [
"132xxxx1280"
],
"isAtAll": False
},
"text": {
"content": text
}
}
print requests.post(api_url,json.dumps(json_text),headers=headers).content
hearders = "User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36"
url = "https://tianqi.moji.com/weather/china/guangdong/shenzhen" ##要爬去天气预报的网址
par = ‘(<meta name="description" content=")(.*?)(">)‘ ##正则匹配,匹配出网页内要的内容
##创建opener对象并设置为全局对象
opener = urllib2.build_opener()
opener.addheaders = [hearders]
urllib2.install_opener(opener)
##获取网页
html = urllib2.urlopen(url).read().decode("utf-8")
##提取需要爬取的内容
data = re.search(par,html).group(2)
msg(data)
拷贝脚本时请去掉注释
运行脚本:
python weather.py
{"errcode":0,"errmsg":"ok"}
钉钉群收到消息如图:
做计划任务:
# crontab -e
no crontab for root - using an empty one
30 8 * * * /usr/bin/python /root/script/weather.py 2> /dev/null > /dev/null
每天早晨8:30自动推送天气预报到钉钉群
以上是关于Python之钉钉机器人推送天气预报的主要内容,如果未能解决你的问题,请参考以下文章