12
21

More than 5 years have passed since last update.

Pythonでスクレイピングした情報をLINE Notifyを使って通知する

Last updated at Posted at 2018-08-15

概要

スクレイピングに関して少し勉強したのでそれを利用した簡単アプリを作成したときのメモです。
今回は例としてYahoo!天気から得た情報をLINEに通知するやり方です。

  • 使用言語 : Python3

手順

スクレイピングの準備

今回はBeautifulSoupを使用しました。スクレイピングの記事は当サイト内でも多数あるのでそちらを参考にしていただければと思います。

天気予報の取得

  • webサイトにアクセス
import requests
from bs4 import BeautifulSoup

r = requests.get('https://example.html')
  • 所望の情報を取得

soup = BeautifulSoup(r.content, "html.parser")

hoge = soup.find_all("p")
date = soup.find_all("p", class_ = "date")

簡単に特定のタグの情報を取得することができます。今回は例としてPタグを取得しています。
また3行目のように属性などをさらに絞ることで取得する情報を指定しやすくなります。
取得した情報はlistとして扱うことができ, 下記のようにすることで文字を取得することも可能です。

today = date.getTest()

日付と同じ要領で天気情報も取得可能です。

LINE Notifyを利用し, 取得したメッセージの通知

以下, pythonを利用したLINEの通知方法です。


LINE_TOKEN =  "取得したトークンを記述する"
LINE_NOTIFY_URL = "https://notify-api.line.me/api/notify"

def send_weather_info(msg):
    method = "POST"
    headers = {"Authorization": "Bearer %s" % LINE_TOKEN}
    payload = {"message": msg}
    try:
        payload = urllib.parse.urlencode(payload).encode("utf-8")
        req = urllib.request.Request(
            url=LINE_NOTIFY_URL, data=payload, method=method, headers=headers)
        urllib.request.urlopen(req)
    except Exception as e:
        print ("Exception Error: ", e)
        sys.exit(1)

最終的なコード


r = requests.get('https://example.html')
soup = BeautifulSoup(r.content, "html.parser")

w_date = soup.find_all("x", class_ = "xxxx")
weather = soup.find_all("x", class_ = "xxxx") # "x", "xxxx"はサイトに合わせて適宜変更してください。

today = w_date[0].getText()
tomorrow = w_date[1].getText()

td_weather = weather[0].getText()
tm_weather = weather[1].getText()

msg = "天気予報\n%s : %s\n%s : %s" % (today, td_weather, tomorrow, tm_weather)

LINE_TOKEN =  "取得したトークンを記述する"
LINE_NOTIFY_URL = "https://notify-api.line.me/api/notify"

def send_weather_information(msg):
    method = "POST"
    headers = {"Authorization": "Bearer %s" % LINE_TOKEN}
    payload = {"message": msg}
    try:
        payload = urllib.parse.urlencode(payload).encode("utf-8")
        req = urllib.request.Request(
            url=LINE_NOTIFY_URL, data=payload, method=method, headers=headers)
        urllib.request.urlopen(req)
    except Exception as e:
        print ("Exception Error: ", e)
        sys.exit(1)

def main():
    send_weather_information(msg)


if __name__ == '__main__':
    main()

こんな感じでLINEに通知が来ました。

IMG_3062.jpg

感想

天気など調べるのが手間だなと思って作成してみました。
ですが, ファイルを実行するのも面倒なので, AmazonDashButtonなどを利用してもっと簡単にできればと思っております。
天気のみならLINEの通知としてよりよい方法があるようなのでそちらも参考にしてまた勉強していきたいと思います。

12
21
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
12
21