LoginSignup
9
12

More than 5 years have passed since last update.

JR西日本の運行状況をPythonで取得

Posted at

1_JR西日本の運行状況を取得
2_遅延のある路線を取得
3_出力
します。

[運行状況引用元]
http://trafficinfo.westjr.co.jp/list.html

xpathを使用してhtmlから運行状況のみ取得しています。
ここの処理でlxmlを使用しました。特に難しくもないのでスクレイピング練習用?にはちょうどいいかもしれません。
またユーザーエージェントにてアクセスする際にiPhoneに見せかけています。
引数として受け取るので自由に変更できます。
また、遅延が一本も無い状態だとreturnをせず(if body:であるから)そのまま関数は処理を終えます。

出力サンプル

[01時26分現在の運行状況]
中国エリア: 遅れ等が発生しています。

コード

GET_JR_INFO.py
#coding: utf-8

import urllib2, lxml.html
from datetime import datetime

def GET_info(user_agent):
    headers = {'User-Agent': user_agent}
    root = lxml.html.fromstring(urllib2.urlopen(urllib2.Request("http://trafficinfo.westjr.co.jp/list.html", None, headers)).read())

    list_data = []
    list_data.append("[{}]".format("".join([i.text for i in root.xpath('//*[@id="contents"]/div[1]/h1')]).encode("utf-8")))
    for i in range(1, 7):
        path_status = '//*[@id="contents"]/div[2]/ul/li[%d]/span[3]' % i
        path_name = '//*[@id="contents"]/div[2]/ul/li[%d]/span[1]' % i
        if not "遅れの情報はありません。" in "".join([i.text for i in root.xpath(path_status)]).encode("utf-8"):
            body = "{}: {}".format(
                "".join([i.text for i in root.xpath(path_name)]).encode("utf-8"),
                "".join([i.text for i in root.xpath(path_status)]).encode("utf-8"))
            list_data.append(body)
    if body:
        return list_data

if __name__ == "__main__":
    print "\n".join(GET_info(
        user_agent="Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A403 Safari/8536.25"
        ))
9
12
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
9
12