六帖のかたすみ

DVを受けていた男性。家を脱出して二周目の人生を生きています。自閉症スペクトラム(受動型)です。http://rokujo.org/ に引っ越しました。

JR東日本のサイトから運行情報をゲットするスクリプト1

retDict = {}

lines = ['東海道線', '中央線快速電車']

import lxml.html
import requests
try:
  target_url = 'http://traininfo.jreast.co.jp/train_info/kanto.aspx'
  target_html = requests.get(target_url).content
  root = lxml.html.fromstring(target_html)
  TblInfo = root.cssselect('#TblInfo')[0]
  trs = TblInfo.cssselect('.px12')
  for tr in trs:
    for line in lines:
      if tr.text_content() == line:
        time = tr.xpath('../../following::tr')[0]
        content = tr.xpath('../../following::tr/following::tr')[0]
        dict = {}
        dict['time'] = time.text_content().rstrip()
        dict['content'] = content.text_content().rstrip()
        retDict[line] = dict
except Exception as ex:
  print(ex)

print(retDict)

実行例

{'中央線快速電車': {'content': '中央線快速電車は、日野駅での人身事故の影響で、上下線で一部列車が運休となっています。', 'time': '2015年5月10日21時49分 配信'}, '東海道線': {'content': '東海道線は、横浜駅での人身事故の影響で、東京〜小田原駅間の下り線の一部列車に遅れがでています。高崎線への直通運転を終日中止します。', 'time': '2015年5月10日21時20分 配信'}}

初めて作成、難しいねぇ。。最も時間がかかったのは、実はlxmlのインストール。
参考サイト:
http://d.hatena.ne.jp/hippu/20091103/1257259317
http://ivis-mynikki.blogspot.jp/2013/03/pythonvcvarsallbat.html