4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PythonでYahooの天気情報を取得+Slackに通知する

Last updated at Posted at 2021-04-11

概要

Yahoo!天気・災害の天気情報をスクレイピングしてSlackに通知出来るようにしました。
(天気情報を取得するAPIは既にありますが、重ね着情報が便利そうだったので今回はYahooさんを利用させてもらいました。)
雨の場合は緑の線が黄色になります。
スクリーンショット 2021-04-12 1.44.51.png

ソースコード

コードは以下の通り。
変更必須箇所は以下の2つ。

# coding: UTF-8
import requests
import json
from bs4 import BeautifulSoup

# webhook url
SLACK_WEBHOOK_URL = 'https://hooks.slack.com/services/**/**'
# weather url
WEATHER_INFO_URL = 'https://weather.yahoo.co.jp/weather/jp/**/****.html'

# Slack通知メッセージ用
fields = []

# スクレイピング
html = requests.get(WEATHER_INFO_URL)
soup = BeautifulSoup(html.content, "html.parser")

# 場所
title = soup.find('title').text;idx = title.find(' -')
place = title[:idx]

main = soup.find('div', id='wrapper').find('div', id='contents').find('div', id='contents-body').find('div', id='main')
# 発表時間
updated_date = main.find('div', class_='yjw_title_h2').find('p').text
# 現時点の天気情報取得
todays_weather = main.find('div', class_='forecastCity').find('table').find('tr').find('td').find('div')
# 日付
date = todays_weather.find('p', class_='date').text
# 天気情報
weather_text = todays_weather.find('img')['alt']
# 天気画像
weather_image_url = todays_weather.find('img')['src']
# 最高気温
highest_temperature = todays_weather.find('ul', class_='temp').find('li', class_='high').text
message = {"title":'最高気温', "value":highest_temperature,"short":False};fields.append(message)
# 最低気温
lowest_temperature = todays_weather.find('ul', class_='temp').find('li', class_='low').text
message = {"title":'最低気温', "value":lowest_temperature,"short":False};fields.append(message)
# 降水情報取得
table = todays_weather.find('table')
# 時間帯
time_rows = table.find('tr', class_='time').find_all('td')
time = [i.text for i in time_rows] # ['0-6', '6-12', '12-18', '18-24']
time_text = '|'.join(time)
# 降水確率
precip_rows = table.find('tr', class_='precip').find_all('td')
precip = [i.text for i in precip_rows]
precip_text = '|'.join(precip)
message = {"title":'降水情報', "value":time_text + '\n' + precip_text,"short":False};fields.append(message)
# 風
wind = todays_weather.find_all('dd')[0].text
message = {"title":'', "value":wind,"short":False};fields.append(message)
# 波
wave = todays_weather.find_all('dd')[1].text
message = {"title":'', "value":wave,"short":False};fields.append(message)

# 花粉情報
#pollen_info = main.find('div', class_='pollenInduction').find('div', class_='pollenInduction_contents') \
#                    .find('div', class_='forecast').find('ul').find('li').find('p', class_='flying').find('span').text
#message = {"title":'花粉情報', "value":pollen_info,"short":False};fields.append(message)

# 指数情報取得
index_info = main.find('div', class_='indexList').find('div', class_='tabView_content')
# 洗濯
washing = index_info.find('dl', class_='indexList_item-laundry').find('dd').find('p', class_='index_text').text
message = {"title":'洗濯', "value":washing,"short":False};fields.append(message)
# 傘
umbrella = index_info.find('dl', class_='indexList_item-umbrella').find('dd').find('p', class_='index_text').text
message = {"title":'', "value":umbrella,"short":False};fields.append(message)
# 重ね着
clothing = index_info.find('dl', class_='indexList_item-clothing').find('dd').find('p', class_='index_text').text
message = {"title":'重ね着', "value":clothing,"short":False};fields.append(message)
# 乾燥
skindried = index_info.find('dl', class_='indexList_item-skindried').find('dd').find('p', class_='index_text').text
message = {"title":'乾燥情報', "value":skindried,"short":False};fields.append(message)

# 色指定
# 雨の場合はwarningにする
color = 'good'
if '' in weather_text:
    color = 'warning'

message = {
    "username":'Weather_Infomation',
    "icon_emoji":':simple_smile:',
    "attachments":[
        {
            "pretext": date + '' + place + 'は、' + weather_text +'です。(' + updated_date + ')',
            "image_url":weather_image_url,
            "color":color,
            "fields":fields
        }
    ]
}
requests.post(SLACK_WEBHOOK_URL, data=json.dumps(message))

Slackのユーザ名やアイコンを変更したい場合はusernameicon_emojiを書き換えればOK。
不要な情報はコメントアウトして消してください。

※Yahoo側でフォーマットの変更があればいつか使えなくなる可能性あり。

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?