LoginSignup
0
0

More than 3 years have passed since last update.

Pythonで天気予報botもどきを作ってみた。

Last updated at Posted at 2020-09-25

Pythonで天気予報bot作ってみた.

タイトル通りPythonで天気予報botを作ってみました(厳密には全然botではないです)。
天気予報を確認することすらめんどくさがってしまう性格で「LINEで送れたらなー」と思っていた所、既に先人の方達がやっていたので、知恵を借りながら(ほぼパクリながら)作ってみました。

やったこと

・スクレイピングでYahooの天気情報を取得
・スクレイピングで取得した情報をLINE Notifyで表示

準備

必要なライブラリのインストール

$pip install beautifulsoup4
$pip install requests

トークンの取得

LINENotifyでトークンを発行しておきます。

コード

import urllib.request
import requests
from bs4 import BeautifulSoup

line_notify_token = 'xxxxxxxxxxxxxxxxxxxxx'#発行したトークンを使います。
line_notify_api = 'https://notify-api.line.me/api/notify'

rssurl = "https://rss-weather.yahoo.co.jp/rss/days/3410.xml"#このコードでは仙台の天気情報を取得します。

URL = "https://weather.yahoo.co.jp/weather/jp/8/3410/8201.html"

tenki = []
detail = []


def Parser(rssurl):
   with urllib.request.urlopen(rssurl) as res:
      xml = res.read()
      soup = BeautifulSoup(xml, "html.parser")
      for item in soup.find_all("item"):
         title = item.find("title").string
         description = item.find("description").string
         if title.find("[ PR ]") == -1:
            tenki.append(title)
            detail.append(description)

def Otenki():
    Parser(rssurl)
    for i in range(0,2):
        message = tenki[i]
        payload = {'message': "\n" + message}
        headers = {'Authorization': 'Bearer ' + line_notify_token}
        line_notify = requests.post(line_notify_api, data=payload, headers=headers)

Otenki()

実行結果

IMG_8243.jpg
しっかり送られてきて嬉しい気持ちになりました。

感想

本当はAWS,Herokuを使って自動化までやりたかったですが...。
知識が何も無い状態で飛び込んで高額請求がきたら対処出来ないので、今回はここまでにしておきました笑。

自分で動かしてみると分からないなりにも色々出来て楽しかったです。またスキルを身に付けていきながらこの記事も更新していきたいです。

追記

Herokuで自動化することが出来たのでまた記事を書こうと思います。

参考記事

【Yahoo!天気リプレース版】LINE Notify + Pythonで天気情報を取得する方法
Pythonで天気予報をLINE通知する

0
0
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
0
0