ダム途中

2021/04/18現在利用できません

import os
import re

import requests
import twitter
from bs4 import BeautifulSoup

url = 'http://i.river.go.jp/_-p01-_/p/ktm1801070/?mtm=10&swd=&prf=3801&twn=3801202&rvr=&den=0972900700006'

headers = {
    'User-Agent':
    'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko'
}

api = twitter.Api(consumer_key=os.environ["DAM_CON_KEY"],
                  consumer_secret=os.environ["DAM_CON_SEC"],
                  access_token_key=os.environ["DAM_ACC_KEY"],
                  access_token_secret=os.environ["DAM_ACC_SEC"])

# 最新ツイートを取得

tweets = api.GetUserTimeline(screen_name='BotTamagawaDam')
text = tweets[0].text

# 前貯水率を抽出

m = re.search(r"(\d+\.?\d*)%", text)

# 前貯水率を数値に変換

if m:
    try:
        brate = float(m.group(1))
    except:
        brate = 0
else:
    brate = 0

r = requests.get(url, headers=headers)

if r.status_code == 200:

    soup = BeautifulSoup(r.content, 'html5lib')

    contents = soup.find('a', {'name': 'contents'}).get_text('\n', strip=True)

    # print(contents)

    # サブタイトル・単位を除去
    _temp = re.sub(r'■\d{1,2}時間履歴\n単位:千m3\n', '', contents)

    lines = [i.split() for i in _temp.splitlines()]

    result = []

    for line in lines:

        try:
            time, _rate = line
            rate = float(_rate)
        except:
            continue

        else:
            result.append({"time": time, "rate": rate})

    # 結果確認
    # print(result)

    n = len(result)

    if n:

        tw = result[0]

        # 最新3件確認

        if n > 2:

            for j in result[:3]:
                if j["time"] in ['6:00', '12:00', '18:00']:
                    tw = j
                    break

        twit = 'ただいまの玉川ダムの貯水率は{0[rate]}%です({0[time]})\n前回比{1:+.1f}ポイント\n#今治 #玉川ダム #貯水率'.format(
            tw, tw["rate"] - brate)

        status = api.PostUpdate(twit)

        print(status.text)