通過Python腳本結合釘釘機器人,定時向釘釘群推送天氣預報
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: aiker@gdedu.ml
# My blog http://m51cto.51cto.blog.com
import requests
import re
import urllib2
import json
import sys
import osheaders = {'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).contenthearders = "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自動推送天氣預報到釘釘群
本文轉自 喵來個魚 51CTO博客,原文鏈接:http://blog.51cto.com/m51cto/2072280,如需轉載請自行聯系原作者