Skip to content

Instantly share code, notes, and snippets.

@ping
Created September 19, 2016 07:15
Show Gist options
  • Save ping/dd9f7b0e02285e1b9ed7272b0253e5a9 to your computer and use it in GitHub Desktop.
Save ping/dd9f7b0e02285e1b9ed7272b0253e5a9 to your computer and use it in GitHub Desktop.
Simple python script to get tracking status from POS Malaysia
import argparse
import re
import json
try:
from urllib2 import urlopen, Request
from urllib import urlencode
except ImportError:
from urllib.request import urlopen, Request
from urllib.parse import urlencode
USER_AGENT = 'Mozilla/5.0'
parser = argparse.ArgumentParser(description='POS MALAYSIA PARCEL TRACKER')
parser.add_argument(
'parcel_ids', metavar='ID', type=str, nargs='+', help='Parcel IDs')
args = parser.parse_args()
track_page = 'http://www.pos.com.my/postal-services/quick-access/?track-trace#trackingIds=' \
+ ';'.join(args.parcel_ids)
track_page_req = Request(track_page, headers={'User-Agent': USER_AGENT})
track_page_res = urlopen(track_page_req)
track_page_content = track_page_res.read().decode('utf-8')
mobj = re.search(r'"X-User-Key":\s+"(?P<key>[a-zA-Z0-9]+)"', track_page_content)
if mobj:
user_key = mobj.group('key')
for parcel_id in args.parcel_ids:
api_endpoint = 'https://apis.pos.com.my/apigateway/as2corporate/api/v2trackntracewebapijson/v1/?' \
+ urlencode({'id': parcel_id, 'Culture': 'en'})
req = Request(api_endpoint, headers={'User-Agent': USER_AGENT, 'X-User-Key': user_key})
res = urlopen(req)
try:
track_info = json.loads(res.read().decode('utf-8'))
print('\nRESULT FOR PARCEL %s:' % parcel_id)
for step in track_info:
if step.get('ErrorDetails'):
print('%(process)s (%(type)s)\n%(errordetails)s' % {
'type': step.get('type'),
'process': step.get('process'),
'errordetails': step.get('ErrorDetails')})
break
else:
print('%(date)s %(process)s @ %(office)s' % {
'date': step.get('date').ljust(30),
'process': step.get('process').ljust(60),
'office': step.get('office').ljust(20)})
print(''.ljust(115, '-'))
except ValueError as e:
print('HTTP%d %s: %s' % (res.code, str(e), res.read()))
break
else:
print('Unable to extract user key')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment