LoginSignup
8
11

More than 5 years have passed since last update.

PythonでXMLから降水確率を取得する

Last updated at Posted at 2017-08-03

親記事: Raspberry Pi Zero Wで傘リマインダーを作る

タイトルの通りです。Python初心者、XMLのこともまだちゃんと理解していない。追々勉強していきます。
使っているPythonのバージョンは2.7.9です。

お世話になったリンク

http://www.drk7.jp/weather/
気象庁が公開している天気予報情報をXML形式で配信しているようです。有難く利用させていただきます。

https://docs.python.jp/2.7/library/xml.etree.elementtree.html
XMLのパースのしかた。

出来上がったコード

横浜東部の降水確率を表示します。自分が知りたいのは主に夕方および夜の降水確率なので、

  • 12時 - 18時
  • 18時 - 24時

の二つに分けて取得します。もっと効率的なやり方がありそうな気配をひしひしと感じます。ご教示をば。

2017/08/13 追記: コメント欄に@shiracamusさんから教えていただいた、内包表記を使ったもっときれいなコードがあります。

code
# coding: utf_8

import datetime
today = datetime.datetime.today().strftime("%Y/%m/%d")

import requests
url = 'http://www.drk7.jp/weather/xml/14.xml'
response = requests.get(url)

import xml.etree.ElementTree as ET
root = ET.fromstring(response.content)

# Get rainfallchance of North Yokohama
# Time: 12h - 18h and 18h - 24h

for area in root.iter('area'):
    if area.get('id').encode('utf_8') == '東部':
        for info in area.findall('info'):
            if info.get('date') == today:
                rainfallchance = info.find('rainfallchance')
                for period in rainfallchance.findall('period'):
                    hour = period.get('hour')
                    if hour == '12-18' or hour == '18-24':
                        print hour + 'h ' + period.text + '%'
result
12-18h 10%
18-24h 20%
8
11
4

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
8
11