Kohei Blog

夫・父親・医療系エンジニア

【Python】楽天カードの請求確定額をLINE Notifyで通知してみた

f:id:kei_01011:20210519083717p:plain カード請求額を毎回チェックするのは面倒なので、LINE Notifyで通知する仕組みを構築中です。

今回まとめるのは以下の部分

最終的に、マネーフォワードから銀行の口座残高や資産状況を取得してきて、毎月の資産を把握できるようにしようかと思っています。

今回はその前段部分です。

楽天カードから請求額をスクレイピング

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import requests
from bs4 import BeautifulSoup
import pandas as pd
from time import sleep
from datetime import datetime

def get_rakuten_bill():
    # password
    USERNAME = 'email@example.com'
    PASSWORD = 'xxxxxxxxxxxxxxxxx'
    error_flg = False

    # open chrome
    options = Options()
    options.add_argument('--headless')
    driver = webdriver.Chrome('/Users/user/driver/chromedriver',options=options)
    target_url = 'https://www.rakuten-card.co.jp/e-navi/index.xhtml'
    driver.get(target_url)
    sleep(3)

    # login
    try:
        username_input = driver.find_element_by_xpath("//input[@name='u']")
        username_input.send_keys(USERNAME)
        sleep(1)
        password_input = driver.find_element_by_xpath("//input[@name='p']")
        password_input.send_keys(PASSWORD)

        login_button = driver.find_element_by_xpath("//input[@type='submit']")
        login_button.submit()
        sleep(1)

    except Exception:
        error_flg = True
        print('ユーザー名、パスワード入力時にエラーが発生しました')

    # 請求書ページを開く
    if error_flg is False:
        try:
            driver.get('https://www.rakuten-card.co.jp/e-navi/members/statement/index.xhtml?tabNo=1&l-id=enavi_top_info-card_statement')
            sleep(3)
        except Exception:
            print('エラーが発生しました')
            # 例外の場合、処理をしない pass
            pass
    # 最新の請求額を取得
    try:
        soup = BeautifulSoup(driver.page_source,'html.parser')
        billing_latest = int(soup.find('span',{'class':'stmt-u-fs-xxl'}).text.replace('\n','').replace(',',''))
        sleep(1)
    except Exception:
        error_flg = True
        print('エラーが発生しました')

    # chrome driver close
    driver.close()
    driver.quit()
    
    return billing_latest

ユーザー名とパスワードはご自身のものに書き換えてください。

楽天カードは、毎月12日に請求額が確定するので、12日以降にスクリプトを実行するようにする予定です。

これで、確定した請求額が取得できます。

LINE Notify で今月の請求額を通知

LINE Notifyはアクセストークンを取得するだけでいいので、とっても簡単に実装できる。

notify-bot.line.me

f:id:kei_01011:20210519082501p:plain

ドキュメントにある、POSTのエンドポイントURLを使用します。

ドキュメント↓ LINE Notify

import requests
def notify_message(message):
    LINE_NOTIFY_TOKEN = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    url = 'https://notify-api.line.me/api/notify'
    headers = {
        'Authorization': f'Bearer {LINE_NOTIFY_TOKEN}'
    }

    data = {
        'message': message
    }
    requests.post(
        url,
        headers=headers,
        data=data
    )

アクセストークンは直書きしてますが、セキュリティを考慮したい人は別ファイルに記述して読み込ませてください。

テスト

f:id:kei_01011:20210519083440p:plain

無事、通知できました。

今月の請求額多いな。。。

また続き書きます。