Skip to content

Instantly share code, notes, and snippets.

@naotea
Last active June 18, 2019 23:45
Show Gist options
  • Save naotea/c8cb2d0b27e866598ff39ce5fd1c2261 to your computer and use it in GitHub Desktop.
Save naotea/c8cb2d0b27e866598ff39ce5fd1c2261 to your computer and use it in GitHub Desktop.
tenki.jpから特定の場所の明日/今日の天気、最高気温、最低気温を取得し、Slackに投稿(ラズパイのcronで定期実行して使ってます)
# coding: UTF-8
#
# tenki.jpから指定場所(url)の明日の天気、最高気温、最低気温を取得し、Slackに投稿する
# cron等で定時起動
#
import urllib.request
from bs4 import BeautifulSoup
from datetime import datetime
import slackweb
#slackの投稿用Webhook urlを設定
slack = slackweb.Slack(url="https://hooks.slack.com/services/........................................")
#tenki.jpの取得先ページ
url = "https://tenki.jp/forecast/3/16/4410/13106/"
#取得先の場所
city = "台東区"
html = urllib.request.urlopen(url)
#13時からは明日の天気。その前は今日の天気を取得
msg = ""
tget = "today-weather"
day = "今日"
dt = datetime.now()
tm = '{0}時{1}分'.format(int(dt.strftime("%I")), dt.minute)
if dt.hour > 12:
tget = "tomorrow-weather"
day = "明日"
#取得先htmlから該当位置の値を読む
soup = BeautifulSoup(html, "html.parser")
tsection = soup.find("section", class_=tget)
telop = tsection.find("p", class_="weather-telop").string
temph = tsection.find("dd", class_="high-temp temp").find("span", class_="value").string
templ = tsection.find("dd", class_="low-temp temp").find("span", class_="value").string
msg = '{0}です。{1}の天気をお知らせします。{2}は{3}、最高気温{4}度、最低気温{5}度です'.format(tm, day, city, telop, temph, templ)
#確認用標準出力
print(datetime.now().strftime("%Y/%m/%d %H:%M:%S") + ' ' + msg)
#slackに投稿
slack.notify(text=msg)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment