ActiveState Code

Recipe 496790: Automatic Southwest Boarding Pass


This script automatically checks you into a Southwest airlines flight exactly 24 hours before the flight. It finds the time of your flight and handles the timing and the web posting automatically with plenty of error checking. All you have to do is provide a confirmation number, first name, and last name. The script will email the results to you if an email address and valid smtp server are provided. The departing or returning flight will be scheduled, whichever is closest to the current time.

Python
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
#! /usr/local/bin/python
# ========================================================================
# (c) Copyright belongs to Ken Washington
# All rights reserved
# ========================================================================

# imports
import os
import re
import sys
import time
import sched
import string
import urllib
import httplib
from HTMLParser import HTMLParser

# ========================================================================
# you MUST change these parameters to the values for your flight
# the DEBUG_SCH should be 0 to run delayed scheduling automatically
# set to 1 to skip the scheduler if we are not within 24 hours
#          immediate calls to the Internet will be made within 24 hrs
# set to 2 to simulate Internet calls. Locally saved .htm files
#          must be present with specific names for this to work
# The names are listed here - they must be EXACTLY as shown
# 1) Southwest Airlines - Retrieve Itinerary.htm
# 2) Southwest Airlines - Schedule.htm
# 3) Southwest Airlines - Check In and Print Boarding Pass.htm
# 4) Southwest Airlines - Print Boarding Pass.htm
# 5) Southwest Airlines - Retrieve-Print Boarding Pass.htm
# ========================================================================
confirmation = 'ABCDEF'
firstname = 'Firstname'
lastname = 'Lastname'
DEBUG_SCH = 2
# ========================================================================
# fill in these parameters if you want the script to email you
# to disable make the emailaddr = None
emailaddr = None
# emailaddr = "myemail@myemail.com"
smtpserver = "smtpserver.com"
smtpauth = False
smtpport = 80
smtpuser = "username"
smtppass = "password"

# ========================================================================
# fixed page locations and parameters - updated to bypass Ajax front page
# DO NOT change these parameters
main_url = 'www.southwest.com'
checkin_url = '/content/travel_center/retrieveCheckinDoc.html'
retrieve_url = '/travel_center/retrieveItinerary.html'
defaultboxes = ["recordLocator", "firstName", "lastName"]
months = "JanFebMarAprMayJunJulAugSepOctNovDec"
# ========================================================================


# =========== function definitions =======================================

# this is a parser for the Southwest pages
class HTMLSouthwestParser(HTMLParser):

    def __init__(self, swdata):
        self._reset()
        HTMLParser.__init__(self)

        # if a web page string is passed, feed it
        if swdata != None and len(swdata)>0:
            self.feed(swdata)
            self.close()

    def _reset(self):
        self.searchtags = {}
        self.hiddentags = {}
        self.searchaction = ""
        self.formaction = ""
        self.is_search = False
        self.textnames = []
        
    # override the feed function to reset our parameters
    # and then call the original feed function
    def feed(self, formdata):
        self._reset()
        HTMLParser.feed(self, formdata)

    # handle tags in web pages
    # this is where the real magic is done
    def handle_starttag(self, tag, attrs):
        if tag=="input":
            ishidden = False
            ischeckbox = False
            istext = False
            issubmit = False
            thevalue = ""
            thename = None
            for attr in attrs:
                if attr[0]=="type":
                    if attr[1]=="hidden":
                        ishidden= True
                    elif attr[1]=="checkbox" or attr[1]=="radio":
                        ischeckbox = True
                    elif attr[1]=="text":
                        istext = True
                    elif attr[1]=="submit":
                        issubmit = True
                elif attr[0]=="name":
                    thename= attr[1]
                    istext = True
                elif attr[0]=="value":
                    thevalue= attr[1]

            # store the tag for search forms separately
            # from the tags for non-search forms
            if ishidden or ischeckbox:
                if self.is_search:
                    self.searchtags[thename] = thevalue
                else:
                    self.hiddentags[thename] = thevalue

            # otherwise, append the name of the text fields
            elif istext and self.is_search==False and issubmit==False:
                self.textnames.append(thename)

        elif tag=="form":
            for attr in attrs:
                if attr[0]=="action":
                    theaction = attr[1]
                    
                    # check to see if this is a search form
                    if theaction.find("search") > 0:
                        self.searchaction = theaction
                        self.is_search = True
                    else:
                        self.formaction = theaction
                        self.is_search = False


# function to send an simple text email message
def sendEmail(wdata, emailaddr, smtpserver, smtpport= 25, \
              smtpauth=False, smtpuser="", smtppass=""):
    import smtplib
    from email.MIMEText import MIMEText

    # Create a text/plain message
    msg = MIMEText(wdata)

    # me == the sender's email address
    # you == the recipient's email address
    msg['Subject'] = 'Results of Southwest checkin script'
    msg['From'] = emailaddr
    msg['To'] = emailaddr
    s = smtplib.SMTP()

    # connect on the designated port - will be 25 or 80
    try:
        s.connect(smtpserver, 80)
    except Exception, connerror:
        print connerror.__class__, connerror
        return False

    if smtpauth:
        try:
            s.login(smtpuser, smtppass)
        except Exception, connerror:
            print connerror.__class__, connerror
            return False
    try:
        s.sendmail(emailaddr, emailaddr, msg.as_string())
    except Exception, connerror:
        print connerror.__class__, connerror
        return False
    
    s.close()
    return True

# this function reads a URL and returns the text of the page
def ReadUrl(host, req):
    wdata = ""

    try:
        conn = httplib.HTTPConnection(host)
        conn.request("GET", req)
        resp = conn.getresponse()
    except:
        print "Error: Cannot connect in GET mode to ", host+req
        sys.exit(1)

    if resp.status == 200:
        wdata = resp.read()
    else:
        print "Error: Cannot read data from ", host+req
        print "Response: ", resp.status, resp.reason
        sys.exit(1)

    return wdata

# this function sends a post just like you clicked on a submit button
def PostUrl(host, req, dparams):
    wdata = ""
    params = urllib.urlencode(dparams)
    headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}

    try:
        conn = httplib.HTTPConnection(host)
        conn.request("POST", req, params, headers)
        resp = conn.getresponse()
    except:
        print "Error: Cannot connect in POST mode to ", host+req
        print "Params = ", dparams
        sys.exit(1)
        
    if resp.status == 200:
        wdata = resp.read()
    else:
        print "Error: Cannot post data to ", host+req
        print "Params = ", dparams
        print "Response: ",resp.status, resp.reason
        sys.exit(1)

    return wdata

def setInputBoxes(textnames, conf_number, first_name, last_name):
    if len(textnames) == 3:
        boxes = textnames
    else:
        boxes = default_boxes

    params = {}
    params[boxes[0]] = conf_number
    params[boxes[1]] = first_name
    params[boxes[2]] = last_name
    
    return params

def airportCodeTZ(code):
    airportzone = {}
    airportzone["ALB"] = "US/Eastern"
    airportzone["ABQ"] = "US/Mountain"
    airportzone["AMA"] = "US/Central"
    airportzone["AUS"] = "US/Central"
    airportzone["BWI"] = "US/Eastern"
    airportzone["BHM"] = "US/Central"
    airportzone["BOI"] = "US/Mountain"
    airportzone["BUF"] = "US/Eastern"
    airportzone["BUR"] = "US/Pacific"
    airportzone["MDW"] = "US/Central"
    airportzone["CLE"] = "US/Eastern"
    airportzone["CMH"] = "US/Eastern"
    airportzone["CRP"] = "US/Central"
    airportzone["DAL"] = "US/Central"
    airportzone["DEN"] = "US/Mountain"
    airportzone["DTW"] = "US/Eastern"
    airportzone["ELP"] = "US/Mountain"
    airportzone["FLL"] = "US/Eastern"
    airportzone["RSW"] = "US/Eastern"
    airportzone["HRL"] = "US/Central"
    airportzone["BDL"] = "US/Eastern"
    airportzone["HOU"] = "US/Central"
    airportzone["IND"] = "US/Eastern"
    airportzone["JAN"] = "US/Central"
    airportzone["JAX"] = "US/Eastern"
    airportzone["MCI"] = "US/Central"
    airportzone["LAS"] = "US/Pacific"
    airportzone["LIT"] = "US/Central"
    airportzone["ISP"] = "US/Eastern"
    airportzone["LAX"] = "US/Pacific"
    airportzone["SDF"] = "US/Eastern"
    airportzone["LBB"] = "US/Central"
    airportzone["MHT"] = "US/Eastern"
    airportzone["MAF"] = "US/Central"
    airportzone["BNA"] = "US/Central"
    airportzone["MSY"] = "US/Central"
    airportzone["ORF"] = "US/Eastern"
    airportzone["OAK"] = "US/Pacific"
    airportzone["OKC"] = "US/Central"
    airportzone["OMA"] = "US/Central"
    airportzone["ONT"] = "US/Pacific"
    airportzone["SNA"] = "US/Pacific"
    airportzone["MCO"] = "US/Eastern"
    airportzone["PHL"] = "US/Eastern"
    airportzone["PHX"] = "US/Arizona"
    airportzone["PIT"] = "US/Eastern"
    airportzone["PDX"] = "US/Pacific"
    airportzone["PVD"] = "US/Eastern"
    airportzone["RDU"] = "US/Eastern"
    airportzone["RNO"] = "US/Pacific"
    airportzone["SMF"] = "US/Pacific"
    airportzone["SLC"] = "US/Mountain"
    airportzone["SAT"] = "US/Central"
    airportzone["SAN"] = "US/Pacific"
    airportzone["SJC"] = "US/Pacific"
    airportzone["SFO"] = "US/Pacific"
    airportzone["SEA"] = "US/Pacific"
    airportzone["GEG"] = "US/Pacific"
    airportzone["STL"] = "US/Central"
    airportzone["TPA"] = "US/Eastern"
    airportzone["TUS"] = "US/Arizona"
    airportzone["TUL"] = "US/Central"
    airportzone["IAD"] = "US/Eastern"
    airportzone["PBI"] = "US/Eastern"

    # use pacific as default if not found
    try:
        TZcode = airportzone[code]
    except:
        TZcode = "US/Pacific"

    return TZcode

def getTimeZones(timeline):
    # Use a regular expression to find the returning Airport
    reap = re.compile("\((...)\)")
    ts = reap.findall(timeline)

    # these values are number of seconds offsets from UTC
    fr_tz = airportCodeTZ(ts[0])
    fr_dest_tz = airportCodeTZ(ts[1])
    return (fr_tz, fr_dest_tz);

# this routine extracts the departure date and time
def getFlightTimes(the_url, conf_number, first_name, last_name):

    now = time.time()
    current_time = time.localtime(now)
    thisyear = current_time[0];
    thismonth = time.strftime("%b",current_time)

    if DEBUG_SCH > 1:
        fd = open("dbg-retrieveItinerary.html","r")
        swdata = fd.read(-1)
        fd.close()
    else:
        swdata = ReadUrl(main_url, the_url)

    if swdata==None or len(swdata)==0:
        print "Error: no data returned from ", main_url+the_url
        sys.exit(1)

    gh = HTMLSouthwestParser(swdata)

    # get the post action name from the parser
    post_url = gh.formaction
    if post_url==None or post_url=="":
        print "Error: no POST action found in ", main_url+the_url
        sys.exit(1)

    # load the parameters into the text boxes
    params = setInputBoxes(gh.textnames, conf_number, first_name, last_name)

    # submit the request to pull up the reservations on this confirmation number
    if DEBUG_SCH > 1:
        fd = open("dbg-viewPnr.htm","r")
        reservations = fd.read(-1)
        fd.close()
    else:
        reservations = PostUrl(main_url, post_url, params)

    if reservations==None or len(reservations)==0:
        print "Error: no data returned from ", main_url+post_url
        print "Params = ", dparams
        sys.exit(1)

    # parse the returned file to grab the dates and times
    # the last word in the table above the first date is "Routing Details"
    # this is currently a unique word in the html returned by the above
    dateloc_0 = reservations.find("Details")
    dateloc_1 = reservations.find("bookingFormText", dateloc_0)
    i1 = reservations.find(">", dateloc_1)
    i2 = reservations.find("<", i1)
    to_date = reservations[i1+1:i2]

    # narrow down the search to the line with the word depart
    timeloc = reservations.find("Depart", dateloc_1)
    timeline = reservations[timeloc:timeloc+80]

    # use a regular expression to find the two times
    tm = re.compile("\d{1,2}\:\d{1,2}[apAP][mM]")
    ts = tm.findall(timeline)
    to_depart_time = ts[0]
    to_arrive_time = ts[1]

    # get the to time zones
    tzones = getTimeZones(timeline);
    to_tz = tzones[0]
    to_dest_tz = tzones[1]

    # beginning of the return location
    postloc = reservations.find("<form",0)
    airloc = reservations.find("airBackground", timeloc)

    # added logic to address connecting flights
    # only picks up the last connection for the destination arrival
    while True:
        timeloc = reservations.find("Depart", timeloc+80)
        if (timeloc < 0): break

        # ran out of destination legs
        if ( (airloc < postloc) and (timeloc > airloc) ):
            timeloc = airloc
            break;

        timeline = reservations[timeloc:timeloc+80]
        ts = tm.findall(timeline)
        to_arrive_time = ts[1]

        # get the return time zones
        tzones = getTimeZones(timeline)
        to_dest_tz = tzones[1]

    # no return flight if this happens
    if ( (airloc < 0) or (airloc > postloc) ):
        print "Warning: No return flight, this script has not been tested for this case"
        print "         but it might work, so use at your own risk..."
        to_year = thisyear
        to_month = to_date[:3]
        # print to_month, " ", thismonth
        if (months.find(to_month) > months.find(thismonth)):
            to_year = to_year - 1
        to_date = to_date + ", "+str(to_year)
        departure = (to_date, to_depart_time, to_arrive_time, to_tz, to_dest_tz, \
                     to_date, to_depart_time, to_arrive_time, to_tz, to_dest_tz )
        return departure
                
    # now find the return flight date and time information
    dateloc_2 = reservations.find("Details", timeloc)
    dateloc_3 = reservations.find("bookingFormText", dateloc_2)
    i1 = reservations.find(">", dateloc_3)
    i2 = reservations.find("<", i1)
    fr_date = reservations[i1+1:i2]

    # return flight times
    timeloc = reservations.find("Depart", dateloc_3)
    timeline = reservations[timeloc:timeloc+80]
    ts = tm.findall(timeline)
    fr_depart_time = ts[0]
    fr_arrive_time = ts[1]

    # get the return time zones
    tzones = getTimeZones(timeline);
    fr_tz = tzones[0]
    fr_dest_tz = tzones[1]

    # added logic to address connecting flights
    # only picks up the last connection for the destination arrival
    while True:
        timeloc = reservations.find("Depart", timeloc+80)
        if (timeloc < 0): break
        timeline = reservations[timeloc:timeloc+80]
        ts = tm.findall(timeline)
        fr_arrive_time = ts[1]

        # get the return time zones
        tzones = getTimeZones(timeline)
        fr_dest_tz = tzones[1]

    # some logic to create the year - we assume if return month
    # is earlier than departure month that it is in a new year
    to_year = thisyear
    fr_year = thisyear
    to_month = to_date[:3]
    fr_month = fr_date[:3]
    if ( (to_month==thismonth) and (months.find(fr_month) < months.find(to_month)) ):
        fr_year = thisyear+1
    if ( (fr_month==thismonth) and (months.find(fr_month) < months.find(to_month)) ):
        to_year = thisyear-1

    # now lets add on the years
    to_date = to_date + ", "+str(to_year)
    fr_date = fr_date + ", "+str(fr_year)  

    # if DEBUG_SCH>1:
    #    print to_month," ",fr_month," ",thismonth," ",to_year," ",fr_year," ",thisyear, " ", to_date, " ", fr_date

    # now we include the time zones so we can create a UTC time conversion later
    departure = (to_date, to_depart_time, to_arrive_time, to_tz, to_dest_tz, \
                 fr_date, fr_depart_time, fr_arrive_time, fr_tz, fr_dest_tz )
    
    return departure

def getBoardingPass(the_url, conf_number, first_name, last_name):

    # read the southwest checkin web site
    if DEBUG_SCH > 1:
        fd = open("dbg-retrieveCheckinDoc.html","r")
        swdata = fd.read(-1)
        fd.close()
    else:
        swdata = ReadUrl(main_url, the_url)

    if swdata==None or len(swdata)==0:
        print "Error: no data returned from ", main_url+the_url
        sys.exit(1)

    # parse the data
    gh = HTMLSouthwestParser(swdata)

    # get the post action name from the parser
    post_url = gh.formaction
    if post_url==None or post_url=="":
        print "Error: no POST action found in ", main_url+the_url
        sys.exit(1)

    # load the parameters into the text boxes by name
    # where the names are obtained from the parser
    params = setInputBoxes(gh.textnames, conf_number, first_name, last_name)

    # submit the request to pull up the reservations
    if DEBUG_SCH > 1:
        fd = open("dbg-selectBoardingPass.htm","r")
        reservations = fd.read(-1)
        fd.close()
    else:
        reservations = PostUrl(main_url, post_url, params)

    if reservations==None or len(reservations)==0:
        print "Error: no data returned from ", main_url+post_url
        print "Params = ", params
        sys.exit(1)

    # parse the returned reservations page
    rh = HTMLSouthwestParser(reservations)

    # Extract the name of the post function to check into the flight
    final_url = rh.formaction

    # the returned web page contains three unique security-related hidden fields
    # plus a dynamically generated value for the checkbox or radio button
    # these must be sent to the next submit post to work properly
    # they are obtained from the parser object
    params = rh.hiddentags
    if len(params) < 4:
        print "Error: Fewer than the expect 4 special fields returned from ", main_url+post_url
        print "Params = ", params
        sys.exit(1)

    # finally, lets check in the flight and make our success file
    if DEBUG_SCH > 1:
        fd = open("dbg-viewBoardingPass.htm","r")
        checkinresult = fd.read(-1)
        fd.close()
    else:
        checkinresult = PostUrl(main_url, final_url, params)

    # write the returned page to a file for later inspection
    if checkinresult==None or len(checkinresult)==0:
        print "Error: no data returned from ", main_url+final_url
        print "Params = ", params
        sys.exit(1)

    # always save the returned file for later viewing
    fd = open("boardingpass.htm","w")
    fd.write(checkinresult)
    fd.close()

    # look for what boarding letter and number we got in the file
    # now we use re for both letter and number
    myre = re.compile("boarding[ABC]\.gif")
    bgroup = myre.findall(checkinresult)
    if (len(bgroup) >0):
        bletter = bgroup[0][8]
    else:
        bletter = "Unknown"

# logic below allows a valid letter and an unknown number
    myre2 = re.compile("boarding(\d).gif")
    bnumarr = myre2.findall(checkinresult)
    if(len(bnumarr) > 0):
        bnumber = bnumarr[0]
    else:
        bnumber = "Unknown"
        
    if (len(bnumarr) > 1):
        bnumber = bnumber + bnumarr[1]

    if len(bgroup)>0:
        msg = "Boarding group = " + bletter + "   Boarding number = " + bnumber
    else:
        msg = "Boarding group and number are unknown"

    # email this information to self if requested
    if DEBUG_SCH==0 and emailaddr:
        try:
            sendEmail(msg, emailaddr, smtpserver, smtpport, smtpauth, smtpuser, smtppass)
        except:
            print "Unable to email result to %s %s" % (first_name, last_name)

    return msg

# determine the time when we can submit checkin successfully
def getDelay(leave_time, now):

    # start with 24 hours before departure and pad it by 2 minutes just to be sure
    sched_time = leave_time - 24.0*3600.0
    sched_time = sched_time + 120.0

    # now = time.time()
    min_left = int(sched_time - now) / 60
    absmin = abs(min_left)
    days = absmin / 60 / 24
    hours = (absmin - days*24*60) / 60
    minutes = absmin - days*24*60 - hours*60
    # print "Departure time: ", time.strftime("%A %B %d, %Y  at  %I:%M %p",leave_time)

    # print a different message if the time to check in ahead of time is in the past
    if ( min_left <= 0 ):
        msg = "You were ready to check in %d days, %d hours, and %d minutes ago." % \
              (days, hours, minutes)
    else:
        msg = "You have %d days, %d hours, and %d minutes remaining to check in." % \
              (days, hours, minutes)

    # print msg
    return sched_time, msg

# print some information to the terminal for confirmation purposes
def displayFlightInfo(to_time, pr_to_time, to_arrive, fr_time, pr_fr_time, fr_arrive, current, current_UTC):
    print "Confirmation number: ", confirmation
    print "Passenger name:      ", firstname, lastname
    print "Current time:        ", current
    print "Current UTC time:    ", current_UTC
    print " "
    print "==========================================================================="
    print "Destination Flight"
    print "==========================================================================="
    print "Departing: ", to_time
    print "Arriving:  ", to_arrive
    print " "
    print "==========================================================================="
    print "Return Flight"
    print "==========================================================================="

    if ( (to_time==fr_time) and (to_arrive==fr_arrive) ):
        print "There is no return flight"
    else:
        print "Departing: ", fr_time
        print "Arriving:  ", fr_arrive
        print " "

    print "==========================================================================="
    print "UTC Flight departure times (used to determine checkin times)"
    print "==========================================================================="
    print "Departing: ", pr_to_time
    if ( (to_time==fr_time) and (to_arrive==fr_arrive) ):
        print "No returning time"
    else:
        print "Returning: ", pr_fr_time
    print "==========================================================================="

# modified paul's routine to use the year from earlier logic
# and replace the Unix specific time zone trick with a generic one
def makedate(monthdayyear, daytime, TZ):

    # the following code doesn't work on Windows
    # os.environ['TZ'] = TZ
    # time.tzset()
    # need to enter number of seconds for each TZ instead

    # set the time zone delta based on the name
    tzdelta = 8
    if ( TZ == "US/Eastern" ):
        tzdelta = 5
    if ( TZ == "US/Central" ):
        tzdelta = 6
    if ( TZ == "US/Mountain" ):
        tzdelta = 7
    if ( TZ == "US/Arizona" ):
        tzdelta = 7
    if ( TZ == "US/Pacific" ):
        tzdelta = 8

    to_time = "%s %s" % (monthdayyear, daytime)
    time_struct = time.strptime(to_time, "%b %d, %Y %I:%M%p")
    timesarray = (time_struct, time.mktime(time_struct)+tzdelta*3600.0)

    # print timesarray[0], " ", timesarray[1], " ", tzdelta, " ", TZ
    return timesarray

# main program
def main():

    # get the departure times in a tuple
    departure = getFlightTimes(retrieve_url, confirmation, firstname, lastname)

    # get the current time
    now = time.time()
    local_time = time.localtime(now)
    local_zone = time.tzname[0]

    current_time = time.gmtime(now)
    now_UTC = time.mktime(current_time)

    # Convert times to UTC times
    times = makedate(departure[0], departure[1], departure[3])
    to_time = time.strftime("%b %d, %Y %I:%M%p ", times[0]) + departure[3]
    leave_time_1 = times[1]
    pr_to_time = time.strftime("%b %d, %Y %I:%M%p UTC", time.localtime(leave_time_1))

    times = makedate(departure[0], departure[2], departure[4])
    to_arrive = time.strftime("%b %d, %Y %I:%M%p ", times[0]) + departure[4]

    times = makedate(departure[5], departure[6], departure[8])
    fr_time = time.strftime("%b %d, %Y %I:%M%p ", times[0]) + departure[8]
    leave_time_2 = times[1]
    pr_fr_time = time.strftime("%b %d, %Y %I:%M%p UTC", time.localtime(leave_time_2))

    times = makedate(departure[5], departure[7], departure[9])
    fr_arrive = time.strftime("%b %d, %Y %I:%M%p ", times[0]) + departure[9]

    current = time.strftime("%b %d, %Y %I:%M%p ", local_time) + local_zone
    pr_current = time.strftime("%b %d, %Y %I:%M%p UTC", current_time)

    # print some information to the terminal for confirmation purposes
    displayFlightInfo(to_time, pr_to_time, to_arrive, fr_time, pr_fr_time, fr_arrive, current, pr_current)

    # find the time when we can check in within the 24 hour time window
    sched_1, msg_depart = getDelay(leave_time_1, now_UTC)

    # get a scheduler object
    sch = sched.scheduler(time.time, time.sleep)

    # schedule the checkin of the flights if it is in the future
    # also we check to see if we have at least an hour before departure
    # if not then we skip to the return flight - if that fails we do nothing
    msg1 = "Please wait for the scheduler to check in the departing flight..."
    msg2 = "Departing flight has been checked in - see boardingpass.htm for details"
    msg3 = ""
    
    # first branch is before first departing flight
    if sched_1 > now_UTC:
        print msg_depart
        ev1 = sch.enterabs(sched_1, 1, getBoardingPass, (checkin_url, confirmation, firstname, lastname))

    # second branch is when we are ready to do departing flight
    elif ( leave_time_1 - 3660.0 ) > now_UTC:
        print msg_depart
        print "Obtaining departing flight boarding pass right now..."
        msg3 = getBoardingPass(checkin_url, confirmation, firstname, lastname)

    # otherwise handle return flight
    elif (leave_time_1 == leave_time_2):
        msg2 = "Departing flight has been checked in - see boardingpass.htm for details"
        msg3 = "There is no return flight"
        
    else:
        # schedule the second pass or call it now if we are within an hour
        msg1 = "Please wait for the scheduler to check in the returning flight..."
        msg2 = "Returning flight has been checked in - see boardingpass.htm for details"
        sched_2, msg_depart = getDelay(leave_time_2, now_UTC)
        print msg_depart
        if sched_2 > now_UTC:
            ev2 = sch.enterabs(sched_2, 1, getBoardingPass, (checkin_url, confirmation, firstname, lastname))
        elif (leave_time_2-3660.0) > now_UTC:
            print "Obtaining returning flight boarding pass right now..."
            msg3 = getBoardingPass(checkin_url, confirmation, firstname, lastname)
        else:
            msg2 = "It is too late to check in the returning flight"

    # run the scheduled events
    # nothing will be printed during this long pause, so run in the background
    if not sch.empty():
        print msg1
        if DEBUG_SCH==0: sch.run()

    print msg2
    print msg3

if __name__=='__main__':
    main()

Discussion

Travellers who fly Southwest airlines know all too well the importance of "getting an A" so they can board in the first boarding group. This will ensure they have room for their large rollerbag overhead to avoide the dreaded "we'll check that for you sir". With this script you will never again miss "getting an A" regardless of when your flight is. All too often the 24 hour mark falls at a time when you are either asleep or in a critical business meeting, or when you just can't get to your computer.

The sched class is used to wait for the right time to submit the request. An alternative approach is to simplify this script to return 0 if the time is okay and 1 if not and then embed it within a shell script or a cron. On Windows this could be put into the windows scheduler. I chose the sched to demonstrate how this simple yet powerful class works to schedule events for precise moments in time. To account for slight variations in time I also implemented a slight delay in the scheduler to ensure we are indeed within the 24 hour time window. The DEBUG_SCH variable is used to test the code with offline content. To use this debug feature you must have locally saved versions of the htm files that Southwest returns with the expected names. For the most part this can be ignored but I left it in to demonstrate how one can test code that depends on network-provided content. This was an essential trick for this script because the only way to test the script was to use it on a real flight within the actual 24 hour time period. I saved the required files from an actual trip and then used them to develop and debug this script offline.

Updated to fix bugs

Comments

  1. 1. At 1:19 p.m. on 25 jun 2006, James Melton said:

    problem. When I attempt to run the module, it stops at the line: to_depart_time = ts[0] and says the index is out of range. What am I doing wrong?

  2. 2. At 10:55 a.m. on 13 jul 2006, craig paxson said:

    Southwest HTML Samples. Does anyone have saved HTML source from the Southwest site for these pages? Obviously, without having a valid flight to check in to or sample source, it is impossible to test the script. Would need sample pages for:

    1) Southwest Airlines - Retrieve Itinerary.htm

    2) Southwest Airlines - Schedule.htm

    3) Southwest Airlines - Check In and Print Boarding Pass.htm

    4) Southwest Airlines - Print Boarding Pass.htm

    5) Southwest Airlines - Retrieve-Print Boarding Pass.htm

    Thanks.

  3. 3. At 6:09 a.m. on 23 jul 2006, Neville Aga said:

    Free html interface to a checkin script available. There is a free web front end to a southwest checkin script at http://www.southwestgroupa.com

  4. 4. At 9:03 p.m. on 10 oct 2006, Ken Washington (the author) said:

    Samples available. I saved html samples from an actual flight and used them to debug this script. They are available on my home page at http://www.kenw.us

  5. 5. At 9:08 p.m. on 10 oct 2006, Ken Washington (the author) said:

    Time format. Your time format is probably set so that the reg expression fails so it doesn't return any times in the expected format. This is a bug that I will fix. In the mean time you can probably tweak the script to read your time format for your region and browser setting. If you do this I'd appreciate seeing what your settings are. This section is also not critical for the operation of the script so you can just comment this out and set the time variables to something bogus, but if you do that of course the script won't tell you what time you are departing, etc.

  6. 6. At 9:09 p.m. on 10 oct 2006, Ken Washington (the author) said:

    dead link. This link is now gone.

  7. 7. At 9:22 a.m. on 12 oct 2006, Neville Aga said:

    Web site front end checkin for Southwest. It is now located at http://www.checkinsooner.com

  8. 8. At 2:18 p.m. on 20 dec 2006, Alexander Rose said:

    Between Years. I think I may have found a little bug. My flight is scheduled to leave in 06 and return in 07, but the script seems to think its all 06... This is what is returns:

    Departure date/time: Dec 29 7:30PM 2006 Arriving: 10:10PM 2006 Return date/time: Jan 3 10:15AM 2006 Arriving: 11:50AM 2006 Current time: Dec 20 12:36PM 2006 You have 8 days, 6 hours, and 56 minutes remaining to check in. Please wait for the scheduler to check in the departing flight...

  9. 9. At 8:32 a.m. on 19 feb 2007, sasa sasa said:

    Is this still working with SWAs current web schema? I can get the script to run and it retrieves the correct flight times, but I get the following when trying to check in:

    Confirmation number: XXXXXX

    Passenger name: XXX XXXXXXX

    Departure date/time: Feb 20 X:XXAM 2007 Arriving: X:XXAM 2007

    Return date/time: Feb 22 X:XXPM 2007 Arriving: XX:XXPM 2007

    Current time: Feb 19 10:23AM 2007

    You were ready to check in 0 days, X hours, and XX minutes ago.

    Obtaining departing flight boarding pass right now...

    Error: Cannot read data from http://www.southwest.com/travel_center/retrieveCheckinDoc.html

    Response: 302 Moved Temporarily

  10. 10. At 9:56 p.m. on 13 apr 2008, Marty Sixkiller said:

    Anyone get this to work? I'm getting the same error message. It prints out the confirmation #, flight times, etc. and then this:

    Obtaining departing flight boarding pass right now... Error: Cannot read data from http://www.southwest.com/travel_center/retrieveCheckinDoc.html Response: 302 Found

    Any ideas?

  11. 11. At 11:28 a.m. on 1 aug 2008, tafkaks said:

    The 302 return code is a temporary redirect. There should be a URL in the 'Location:' header of the response. ReadURL probably needs to be changed to honor a 302 data return. So basically, if you get a 302, refetch the URL contained in Location:

  12. 12. At 8:28 p.m. on 1 aug 2008, Derrick Burns said:

    The boarding pass letter and number parsing is broken now. Replace lines 388-398 with: myre = re.compile("boarding[ABC].gif") bgroup = myre.findall(checkinresult) bletter = bgroup[0][8]

    myre2 = re.compile("boarding[0123456789]\.gif")
    bnum = myre2.findall(checkinresult)
    bnumber = reduce( lambda x,y: x+y, [f[8] for f in bnum])
    msg = "Boarding group = " + bletter + "   Boarding number = " + bnumber
    
  13. 13. At 8:29 p.m. on 1 aug 2008, Derrick Burns said:

    The boarding pass letter and number parsing is broken now. Replace lines 388-398 with:

    myre = re.compile("boarding[ABC]\.gif")
    bgroup = myre.findall(checkinresult)
    bletter = bgroup[0][8]
    
    myre2 = re.compile("boarding[0123456789]\.gif")
    bnum = myre2.findall(checkinresult)
    bnumber = reduce( lambda x,y: x+y, [f[8] for f in bnum])
    msg = "Boarding group = " + bletter + "   Boarding number = " + bnumber
    
  14. 14. At 7:06 a.m. on 10 aug 2008, Marty Sixkiller said:

    It looks like line 50 needs to be fixed, too, adding 'content' to the front part of the checkin_url:

    BAD:

    checkin_url = '/travel_center/retrieveCheckinDoc.html'

    CORRECTION:

    checkin_url = '/content/travel_center/retrieveCheckinDoc.html'

  15. 15. At 8:25 p.m. on 23 sep 2008, Paul said:

    I spent a few hours today updating this script to better suit my needs. Patch against original available at link below (too large to post).

    Changes:

    1. Check in all people with the same itinerary and confirmation number.
    2. Send boarding pass in email. Can be printed directly from email.
    3. Southwest's web site lists times local to the airports. Use proper time zones and do time math in UTC.
    4. Stick around to automatically check in return flight instead of exiting after checking in departing flight.
    5. Can now send confirmation email with boarding pass to multiple addresses.
    6. Incorporated above updates to fix boarding pass parsing and correct itinerary URL.
    7. Keep trying every 60 seconds if the script can't check in yet (too early). Previously just quit (WTF?!)

    Patch URL: http://laufernet.com/~paul/southwest-checkin.patch

    Not guaranteed, use at your own risk, etc...

  16. 16. At 9:40 a.m. on 28 sep 2008, Dick Fletcher said:

    Paul, I'm kind of new at this so I apologize if this is a dumb question. Is there an easy way to run the .patch file you created? I downloaded the file and saved it as a .py file. I assume the "-" and "+" inside the file indicate lines added and deleted. Other than manually going through each line, is there an easier way to do this? Also, they way I did it, the indentations were all screwed up... Anyway, went through every line manually (i.e. deleted entire lines that had a "-" in front of them and then delete the "+" or delete a space in front of pretty much every line) but when finished, it doesn't do anything, not even an error message. Any help for a novice with determination would be appreciated.

    Cheers

  17. 17. At 7:58 a.m. on 10 oct 2008, Paul said:

    Dick,

    Sorry for the long delay, but this is the first time I've checked back in since the last posting.

    The patch file is an input to the "patch" program. See http://www.freebsd.org/cgi/man.cgi?query=patch&sektion=1 for the manual page. To use it you need Ken Washington's original unmodified checkin script download above (recipe-496790-1.py) and an unmodified copy of my patch file (southwest-checkin.patch), linked in my comment above. Then run the following command in the directory where both files are saved:

    patch < southwest-checkin.patch
    

    The command will apply my changes to Ken's original script. You should then be able to open his script, add in your flight check in information, and use it per his instructions.

    I'm using a patch file because I don't have the original author's permission to redistribute his code. Thus, I only distribute my modifications to his code. The patch program applies the changes I made to his original code automatically.

    There is a Windows version of patch available here: http://gnuwin32.sourceforge.net/packages/patch.htm and Linux and MacOS/X versions are of course also available.

    -Paul

  18. 18. At 5:13 p.m. on 19 oct 2008, bill said:

    To all:

    I am new to Python and have no experience implementing it. I have familiarity with PHP and PERL and perhaps the rules are similar. I would appreciate any help in setting up this program.

    As Paul mentions:

    There is a Windows version of patch available here: http://gnuwin32.sourceforge.net/packages/patch.htm and Linux and MacOS/X versions are of course also available.

    I was unable to find a Mac compatible version.

  19. 19. At 11:12 a.m. on 20 oct 2008, Mark Saunders said:

    I'm unable to get the patch to work, I get the following error (windows platform):

    C:\wamp\www\southwest>patch < southwest-checkin.patch patching file recipe-496790-1.py Assertion failed: hunk, file ../patch-2.5.9-src/patch.c, line 354

    This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.

    Paul, is there any way you can post the patched code. Thanks, Mark

  20. 20. At 9:21 p.m. on 13 nov 2008, Ken 2 said:

    Paul, thanks for all the work, but now it barfs on "one-way" itineraries, which are often unavoidable. Any chance of you working up another patch that lets the script accommodate both? :-) I'll try too, but I've never used Python before....

    Bill, OS X includes patch and Python and manpages for them, no setup required. What Paul said to apply the patch and what the script comments say to enter your itinerary info is all there is to do.

    Mark, as Paul said it's illegal to publish the the code, but there could be something wrong with your patch program, your script file, or your patch file. I'd try re-downloading all three. And check the system requirements of the patch program, maybe your machine is incompatible. (I don't have a PC....)

    Good luck.

  21. 21. At 8:08 a.m. on 19 nov 2008, martin said:

    Mark S.,

    The error you're seeing appears to be because the patch has unix formatting rather than Windows formattint -- Windows requires carriage return / linefeed at the end of each line, whereas unix does not. I fixed this by using Textpad to open the patch then re-save as a Windows text file. After this change the error goes away.

    On the other hand, I'm not able to run the code. I get the following:

    Traceback (most recent call last):
    
      File "zzzz.py", line 674, in <module>
    
        main{}
    
      File "zzzz.py", line 604, in main
    
        times = makedate(departure[0], departure[1], departure[3])
    
      File "zzzz.py", line 582, in makedate
    
        time.tzset()
    
    AttributeError: 'module' object has no attribute 'tzset'
    

    I don't know enough about python to suggest a fix.

    Martin

  22. 22. At 8:26 a.m. on 19 nov 2008, martin said:

    Followup:

    It appears that time.tzset() is not supported in Windows.

    Martin

  23. 23. At 5:18 p.m. on 2 dec 2008, Sander Liebert said:

    I ran the patch using gnuwin32 after changing the patch file to the correct windows format but I did get one error "Hunk #9 FAILED at 407. 1 out of 16 hunks FAILED -- saving rejects to file recipe-496790-1.py.rej

    Do I need to be concerned with this error?

    ***************
    

    * 301,309 ** ts = tm.findall(timeline) fr_depart_time = ts[0] fr_arrive_time = ts[1]

    • departure = (to_date, to_depart_time, to_arrive_time, \
    • fr_date, fr_depart_time, fr_arrive_time)

      return departure

    --- 407,430 ---- ts = tm.findall(timeline) fr_depart_time = ts[0] fr_arrive_time = ts[1] + + # Use a regular expression to find the returning Airport + reap = re.compile("((...))") + ts = reap.findall(timeline) + fr_tz = airportCodeTZ(ts[0]) + fr_dest_tz = airportCodeTZ(ts[1]) + + if(len(fr_tz) < 1): + print "Error, could not find timezone for airport code ", ts[0], ". Using PST" + fr_tz = "US/Pacific" + if(len(fr_dest_tz) < 1): + print "Error, could not find timezone for airport code ", ts[1], ". Using PST" + fr_dest_tz = "US/Pacific"

    • departure = (to_date, to_depart_time, to_arrive_time, to_tz, to_dest_tz, \
    • fr_date, fr_depart_time, fr_arrive_time, fr_tz, fr_dest_tz)
      • print "Departure: ", departure

        return departure

  24. 24. At 1:48 p.m. on 23 dec 2008, Anonymous said:

    I am getting the following error.

    It seems as though the itinerary can't be pulled.

    Traceback (most recent call last):
      File "./recipe-496790-1.py", line 674, in <module>
        main()
      File "./recipe-496790-1.py", line 597, in main
        departure = getFlightTimes(retrieve_url, confirmation, firstname, lastname)
      File "./recipe-496790-1.py", line 409, in getFlightTimes
        fr_arrive_time = ts[1]
    IndexError: list index out of range
    
  25. 25. At 9:44 a.m. on 25 dec 2008, Jeremy Lee said:

    I'm getting the same thing :(

    Traceback (most recent call last): File "./recipe-496790-1.py", line 672, in ? main() File "./recipe-496790-1.py", line 595, in main departure = getFlightTimes(retrieve_url, confirmation, firstname, lastname) File "./recipe-496790-1.py", line 406, in getFlightTimes fr_depart_time = ts[0] IndexError: list index out of range

    Any ideas how to fix this?

  26. 26. At 9:58 a.m. on 25 dec 2008, Jeremy Lee said:

    With debugging on:

    Traceback (most recent call last):

    File "./recipe-496790-1.py", line 672, in ? main()

    File "./recipe-496790-1.py", line 595, in main departure = getFlightTimes(retrieve_url, confirmation, firstname, lastname)

    File "./recipe-496790-1.py", line 328, in getFlightTimes fd = open("Southwest Airlines - Retrieve Itinerary.htm","r")

    IOError: [Errno 2] No such file or directory: 'Southwest Airlines - Retrieve Itinerary.htm'

  27. 27. At 10:38 p.m. on 31 dec 2008, Ken Washington (the author) said:

    Hey everybody!! Wow -- when I posted this simple little script more than 2 years ago I had no idea the interest in it would last this long. I really appreciate all the comments and patches to get this to work with the new Southwest web site. One of my New Year's resolutions is to get back into programming so I will see if I can help resolve some of the issues. Now that I see there is still demand for this free script (many other pay services are out there) it will be fun again to jump back into this. When I first wrote this I had visions to putting a nice TK front end on it too so maybe I'll do that too. Looks like Paul made some nice updates so I'll start there. Any other requests? Again, thanks everybody and stay tuned for more. Ken

    PS - thanks to Sander for pointing this all out to me. I thought this script was dead and buried... :)

  28. 28. At 8:49 p.m. on 1 jan 2009, Ken Washington (the author) said:

    Okay, I've updated the original script. I used many of the ideas and updates posted here over the last few years, but found that several other updates were needed to make it work right. The time zones were not working at all and Paul's update only worked on Unix/Linux systems so I wrote a generic fix. I also implemented correct code to handle year boundaries and to address multiple connection flights. Finally, I also added some code to check for no return flights, but I haven't tested it because I haven't flown one-way recently on SW. I will post the update later tonight.

  29. 29. At 4:34 p.m. on 5 jan 2009, Jeremy Lee said:

    Cool! Thanks Ken! The second time I used it, over the course of a roundtrip flight, everything seemed to work. The first time I ran it unpatched and I don't think it worked though. It was the one-way flight that I had issues with where I posted the last couple comments. It just bailed out completely. Hopefully it will have been fixed :D Unfortunately, I have no immediate plans to fly anywhere as of yet, but hopefully the script will still be working when I do!

    Thanks for making this! It's a really sweet idea!

  30. 30. At 8:54 p.m. on 19 jan 2009, Ken Washington (the author) said:

    You're welcome Jeremy. I have to admit that it had tons of bugs. The version I posted on Jan 1 also was buggy. I ended up rewriting the whole thing again and this time I added a GUI and used Threads for the timer. I also added support for single leg flights and multiple leg flights and multiple passengers. I didn't get to adding the nice email and htm features that Paul added back in September. Maybe later, but it isn't needed to do what I wanted it for. There are so many changes that I think I will post this as a new recipe.

Sign in to comment