Showing posts with label cityrail. Show all posts
Showing posts with label cityrail. Show all posts

Thursday, September 2, 2010

Sydney Cityrail (131500) Timetable on Command-line (Python version) v0.2

    1 #!/usr/bin/python
    2 
    3 import sys
    4 import getopt
    5 import time
    6 import re
    7 
    8 from BeautifulSoup import BeautifulSoup, Comment
    9 import urllib
   10 import urllib2
   11 
   12 
   13 def strip_comments(soup):
   14  comments = soup.findAll(text=lambda text:isinstance(text, Comment))
   15  [comment.extract() for comment in comments]
   16  return soup
   17 
   18 def show_timetable(html, from_sta):
   19 
   20  ## PARSE
   21  soup = BeautifulSoup(BeautifulSoup(html).prettify())
   22  regex = re.compile("\&nbsp",re.I)
   23 
   24  ## FINDING OPTIONS
   25  options = []
   26  div1s = soup.findAll("div",{ "class" : "boxhead tal iewfix2" })
   27 
   28  for d1 in div1s:
   29   option = d1.find("h2").renderContents().encode("ASCII").strip()
   30   options.append(option)
   31 
   32 
   33  ## FINDING TIMETABLE
   34  timetable = []
   35  div2s = soup.findAll("div",{ "class" : "boxbody iewfix" })
   36 
   37  for d2 in div2s:
   38   bs = d2.findAll("b")
   39   for b in bs:
   40    tmp = b.renderContents().encode("ASCII").strip()
   41    tmp = regex.sub("",tmp)
   42 
   43    # fixing "Sydney Terminal" / "Central Station" dilemma
   44    if tmp.find("Sydney Terminal") > 0:
   45     tmp = tmp.replace("Sydney Terminal", "Central Station (Sydney Terminal)
   46     ")
   47    elif tmp.find("Central Station") > 0:
   48     tmp = tmp.replace("Central Station", "Central Station (Sydney Terminal)
   49     ")
   50 
   51    timetable.append(tmp)
   52 
   53 
   54  ## DIPLAY
   55  a_regex = re.compile(from_sta,re.I)
   56 
   57  j=0
   58  for i in xrange(0,len(timetable)):
   59   if a_regex.search(timetable[i]):
   60    print "\n  [[ %s ]]" % (options[j])
   61    j = j + 1
   62 
   63   print timetable[i]
   64 
   65 def usage():
   66  print """
   67  [*] usage: %s  options
   68 
   69  OPTIONS:
   70  -u      print url
   71  -h      show this message
   72 
   73  -a      set from station
   74  -b      set dest. station
   75 
   76  -t      set search time (08:30:AM)
   77    hour, min, sec must be seperated by colon (:)
   78 
   79  -d      set search date (yyyy/mm/dd)
   80    yyyy = 4 digits
   81    mm = 2 digits
   82    dd = 2 ditigs
   83 
   84  EXAMPLE:
   85  %s -a central -b 'town hall' -d 2010/09/02 -t 05:30:PM
   86   """ % (sys.argv[0], sys.argv[0])
   87 
   88 def prepare_param(args):
   89  ## PRESET VARIABLES
   90  print_url = False
   91  from_sta = "redfern"
   92  to_sta = "blacktown"
   93  now_time = time.strftime("%H:%M:%p")
   94  now_date = time.strftime("%Y/%m/%d")
   95 
   96 
   97  ## PARSE COMMAND LINE ARGS
   98  try:
   99   opts, args = getopt.getopt(sys.argv[1:], "a:b:d:t:uh")
  100 
  101  except getopt.GetoptError, err:
  102   print str(err)
  103   usage()
  104   sys.exit(2)
  105 
  106  for opt, arg in opts:
  107   if opt in ("-a"):
  108    from_sta = arg
  109   elif opt in ("-b"):
  110    to_sta = arg
  111   elif opt in ("-h"):
  112    usage()
  113    sys.exit(-1)
  114   elif opt in ("-u"):
  115    print_url = True
  116   elif opt in ("-t"):
  117    now_time = arg
  118   elif opt in ("-d"):
  119    now_date = arg
  120   else:
  121    assert False, "unhandled option"
  122 
  123  ## BREAK TIME INTO HOUR, MIN, AM/PM
  124  try:
  125   now_hour = re.split(":", now_time)[0]
  126   now_min = re.split(":", now_time)[1]
  127   now_ampm = re.split(":", now_time)[2]
  128  except:
  129   print "Incorrect time format"
  130   sys.exit(-1)
  131 
  132  now_date = re.sub("[^0-9]","",now_date)
  133 
  134  return from_sta, to_sta, now_date, now_hour, now_min, now_ampm, print_url
  135 
  136 def fetch_html( from_sta,
  137     to_sta,
  138     now_date,
  139     now_hour,
  140     now_min,
  141     now_ampm):
  142 
  143  url = "http://www.131500.com.au/plan-your-trip/trip-planner?"
  144  values = { "session" : "invalidate",
  145     "itd_cmd" : "invalid",
  146     "itd_includedMeans" : "checkbox",
  147     "itd_inclMOT_5" : "1",
  148     "itd_inclMOT_7" : "1",
  149     "itd_inclMOT_1" : "1",
  150     "itd_inclMOT_9" : "1",
  151     "itd_anyObjFilter_origin" : "2",
  152     "itd_name_origin" : from_sta ,
  153     "itd_anyObjFilter_destination" : "2",
  154     "itd_name_destination" : to_sta,
  155     "itd_itdDate" : now_date,
  156     "itd_itdTripDateTimeDepArr" : "dep",
  157     "itd_itdTimeHour" : now_hour,
  158     "itd_itdTimeMinute" : now_min,
  159     "itd_itdTimeAMPM" : now_ampm,
  160     "x" : "56",
  161     "y" : "11"
  162     }
  163  data = urllib.urlencode(values)
  164  try:
  165   req = urllib2.Request(url, data)
  166  except:
  167   print "Server Error", error
  168   sys.exit(-1)
  169 
  170  response = urllib2.urlopen(req)
  171  html = response.read()
  172 
  173  return html, url, data
  174 
  175 def main(args):
  176  from_sta, to_sta, now_date, now_hour, now_min, now_ampm, print_url =
  177  prepare_param(args)
  178 
  179  print
  180  print "From Station:", from_sta.title()
  181  print "To Station:", to_sta.title()
  182  print "Time:", "%s:%s:%s" % (now_hour, now_min, now_ampm)
  183  print "Date: %s/%s/%s" % (now_date[:4], now_date[4:6],now_date[-2:])
  184 
  185  html, url, data = fetch_html(from_sta, to_sta, now_date, now_hour, now_min,
  186  now_ampm)
  187  if print_url:
  188   print "\n%s%s" % (url, data)
  189 
  190  show_timetable(html, from_sta)
  191 
  192 
  193 if __name__ == "__main__":
  194   main(sys.argv[1:])





Tuesday, August 24, 2010

Sydney Cityrail (131500) Timetable on Command-line (ver: 0.2)

Sydney CiryRail (www.131500.info) changed how parameters are fed in the URL from user's browser which broke my previous command line attempt.

Changes in this version:
  • Time format to use with '-t' is: "16:00" or "04:08:pm"
  • Date format to use with '-d' is: "2010:08:24"
Here is a fixed version (0.2) of the script:

    1 #!/bin/bash -e
    2 
    3 print_url=0
    4 timeout=10
    5 
    6 from_sta='Central'
    7 dest_sta='Town+Hall'
    8 
    9 old_now_date=$(date +%d%%2F%m%%2F%y)
   10 old_now_time=$(date +%I%%3A%M%p)
   11 
   12 now_date=$(date +%Y%m%d)
   13 now_hour=$(date +%I)
   14 now_min=$(date +%M)
   15 now_ampm=$(date +%P)
   16 
   17 function usage()
   18 {
   19 echo
   20 cat <<EOF
   21 [*] usage: `basename $0`  options
   22 
   23 OPTIONS:
   24  -u print url
   25  -h show this message
   26  -a set from station
   27  -b set dest. station
   28  -t set search time (08:30AM)
   29  -d set search date (21/5/10)
   30 EOF
   31 echo
   32 exit
   33 }
   34 
   35 function get_cookie()
   36 {
   37  wget -q -O /dev/null --keep-session-cookies --save-cookies="cookie.txt" "${
   38  1}"
   39 }
   40 
   41 while getopts "uha:b:t:d:" flag
   42 do
   43  if [ "$flag" == 'u' ]
   44  then
   45   print_url=1
   46  fi
   47 
   48  if [ "$flag" == 'h' ]
   49  then
   50   usage
   51  fi
   52 
   53  if [ "$flag" == 'a' ]
   54  then
   55   A=$(echo -n "${OPTARG:0:1}" | tr "[:lower:]" "[:upper:]")
   56   from_sta="$(echo -n "${A}${OPTARG:1}" | sed 's/ /+/g')"
   57  fi
   58 
   59  if [ "$flag" == 'b' ]
   60  then
   61   A=$(echo -n "${OPTARG:0:1}" | tr "[:lower:]" "[:upper:]")
   62   dest_sta="$(echo -n "${A}${OPTARG:1}" | sed 's/ /+/g')"
   63  fi
   64 
   65  if [ "$flag" == 't' ]
   66  then
   67   now_time=$(echo -n "$OPTARG" | tr '[:lower:]' '[:upper:]')
   68   now_time=$(echo "$now_time" | sed 's/://g;s/\-//g;s/\///g;s/\\//g')
   69 
   70   now_hour=$(echo -n "${now_time:0:2}")
   71   now_min=$(echo -n "${now_time:2:2}")
   72   now_ampm=$(echo -n "${now_time:4:2}")
   73  fi
   74 
   75  if [ "$flag" == 'd' ]
   76  then
   77   now_date="$OPTARG"
   78   now_date=$(echo "$now_date" | sed 's/://g;s/\-//g;s/\///g;s/\\//g')
   79  fi
   80 done
   81 
   82 old_url="http://www.131500.com.au/fullEnquiry.asp?&Vehicle=Bus,Train,
   83 Ferry&WalkSpeed=NORMAL&&IsAfter=A&MaxChanges=-
   84 1&FromLocType=s&ToLocType=s&x=64&y=11&FromLoc=$from_sta+Station~~;$from_sta+
   85 Station;$from_sta+Station~~LOCATION&ToLoc=$dest_sta+Station~~;$dest_sta+
   86 Station;$dest_sta+Station~~LOCATION&Time=$now_time&Date=$now_date"
   87 
   88 ori_url='http://www.131500.com.au/plan-your-trip/trip-
   89 planner?session=invalidate&itd_cmd=invalid&itd_includedMeans=checkbox&itd_in
   90 clMOT_5=1&itd_inclMOT_7=1&itd_inclMOT_1=1&itd_inclMOT_9=1&itd_anyObjFilter_o
   91 rigin=2&itd_name_origin=central&itd_anyObjFilter_destination=2&itd_name_dest
   92 ination=redfern&itd_itdDate=20100824&itd_itdTripDateTimeDepArr=dep&itd_itd
   93 TimeHour=2&itd_itdTimeMinute=0&itd_itdTimeAMPM=pm&x=56&y=11'
   94 
   95 url="http://www.131500.com.au/plan-your-trip/trip-
   96 planner?session=invalidate&itd_cmd=invalid&itd_includedMeans=checkbox&itd_in
   97 clMOT_5=1&itd_inclMOT_7=1&itd_inclMOT_1=1&itd_inclMOT_9=1&itd_anyObjFilter_o
   98 rigin=2&itd_name_origin=${from_sta}
   99 &itd_anyObjFilter_destination=2&itd_name_destination=${dest_sta}
  100 &itd_itdDate=${now_date}&itd_itdTripDateTimeDepArr=dep&itd_itdTimeHour=${
  101 now_hour}&itd_itdTimeMinute=${now_min}&itd_itdTimeAMPM=${now_ampm}
  102 &x=56&y=11"
  103 
  104 if [ $print_url == '1' ]
  105 then
  106  echo $url
  107 fi
  108 
  109 echo
  110 echo "From: $from_sta Station"
  111 echo "Dest: $dest_sta Station"
  112 echo "Time: $(echo $now_hour:$now_min $now_ampm | sed 's/\%3A/:/g')"
  113 echo "Date: $(echo ${now_date:0:4}:${now_date:4:2}:${now_date:6:2} | sed
  114 's/\%2F/\//g')"
  115 echo
  116 
  117 referer='http://www.131500.com.au/'
  118 agent='Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.8)
  119 Gecko/20100722 Firefox/3.6.8 (.NET CLR 3.5.30729)'
  120 
  121 #get_cookie $url
  122 #wget $url -q -O - --referer "$referer" --load-cookies=cookie.txt --user-
  123 agent="$agent" | html2text | grep 'Option \([0-9]\+\)\|Arr:\|Dep:'
  124 lynx -noredir -dump $url | grep 'Option \([0-9]\+\)\|Arr:\|Dep:'
  125 
  126 echo

Wednesday, June 30, 2010

Sydney Cityrail (131500) Timetable on Command-line

You need "Lynx" installed. On Debian/Ubuntu, you can do "apt-get install Lynx".

Example usage:
  • Put a '+' between the words, if the station name is not a single word.
  • '-h' shows you the help.
  • By default, it uses current date,time and Redfern-Blacktown stations as from-to combination. The station-name variables are easily editable on top of the script.
babil@quad:~$ train.sh -h

[*] usage: train.sh options

OPTIONS:
-u print url
-h show this message
-a set from station
-b set dest. station
-t set search time (08:30AM)
-d set search date (21/5/10)


babil@quad:~$ train.sh -a redfern -b north+sydney -d 2/7/2010 -t 14:00

From: Redfern Station
Dest: North+sydney Station
Time: 14:00
Date: 2/7/2010

Option 1 : 15 minutes
Dep: 2:00pm Redfern Station Platform 3
Arr: 2:15pm North Sydney Station Platform 4
Option 2 : 15 minutes
Dep: 2:04pm Redfern Station Platform 3
Arr: 2:19pm North Sydney Station Platform 4
Option 3 : 15 minutes
Dep: 2:15pm Redfern Station Platform 3
Arr: 2:30pm North Sydney Station Platform 4
Option 4 : 15 minutes
Dep: 2:19pm Redfern Station Platform 3
Arr: 2:34pm North Sydney Station Platform 4
Option 5 : 21 minutes
Dep: 2:20pm Redfern Station Platform 5
Arr: 2:28pm Wynyard Station Platform 6
Dep: 2:35pm Wynyard Station Platform 4
Arr: 2:41pm North Sydney Station Platform 4
Here's is the script:
    1 #!/bin/bash
2
3 print_url=0
4
5 from_sta='Central'
6 dest_sta='Town+hall'
7 now_date=$(date +%d%%2F%m%%2F%y)
8 now_time=$(date +%I%%3A%M%p)
9
10 function usage()
11 {
12 echo
13 cat <<EOF
14 [*] usage: `basename $0` options
15
16 OPTIONS:
17 -u print url
18 -h show this message
19 -a set from station
20 -b set dest. station
21 -t set search time (08:30AM)
22 -d set search date (21/5/10)
23 EOF
24 echo
25 exit
26 }
27
28 while getopts "uha:b:t:d:" flag
29 do
30 if [ "$flag" == 'u' ]
31 then
32 print_url=1
33 fi
34
35 if [ "$flag" == 'h' ]
36 then
37 usage
38 fi
39
40 if [ "$flag" == 'a' ]
41 then
42 A=$(echo -n "${OPTARG:0:1}" | tr "[:lower:]" "[:upper:]")
43 from_sta="$(echo -n "${A}${OPTARG:1}" | sed 's/ /+/g')"
44 fi
45
46 if [ "$flag" == 'b' ]
47 then
48 A=$(echo -n "${OPTARG:0:1}" | tr "[:lower:]" "[:upper:]")
49 dest_sta="$(echo -n "${A}${OPTARG:1}" | sed 's/ /+/g')"
50 fi
51
52 if [ "$flag" == 't' ]
53 then
54 now_time="$(echo -n "$OPTARG" | tr "[:lower:]" "[:upper:]")"
55 fi
56
57 if [ "$flag" == 'd' ]
58 then
59 now_date="$OPTARG"
60 fi
61 done
62
63 url="http://www.131500.com.au/fullEnquiry.asp?&Vehicle=Bus,Train,
64 Ferry&WalkSpeed=NORMAL&&IsAfter=A&MaxChanges=-
65 1&FromLocType=s&ToLocType=s&x=64&y=11&FromLoc=$from_sta+Station~~;$from_sta+
66 Station;$from_sta+Station~~LOCATION&ToLoc=$dest_sta+Station~~;$dest_sta+
67 Station;$dest_sta+Station~~LOCATION&Time=$now_time&Date=$now_date"
68
69 if [ $print_url == '1' ]
70 then
71 echo $url
72 fi
73
74 echo
75 echo "From: $from_sta Station"
76 echo "Dest: $dest_sta Station"
77 echo "Time: $(echo $now_time | sed 's/\%3A/:/g')"
78 echo "Date: $(echo $now_date | sed 's/\%2F/\//g')"
79 echo
80
81 lynx -dump $url | grep 'Option \([0-9]\+\)\|Arr:\|Dep:'
82
83 echo