[파이썬] 우체국택배 배송정보 가져오는 코드

by Taylor
0 comment

파이썬으로 만든 우체국택배 택배 배송정보를 가져오는 코드입니다.

택배 송장번호를 입력하시면 배송정보를 가져옵니다.

아래 주소에서 더 예쁘게 보실수 있습니다.

https://gist.github.com/taylor224/704e46a627519d035eb9

# -*- coding: utf8 -*-

 
import urllib, httplib, BeautifulSoup
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
 
realurl = 'http://service.epost.go.kr/trace.RetrieveRegiPrclDeliv.postal?sid1='
posturl = 'trace.epost.go.kr'
 
 
def getpost(sid):
params = {
'target_command' : 'kpl.tts.tt.epost.cmd.RetrieveOrderConvEpostPoCMD',
'sid1' : sid,
'RE_ORDID' : 'null'
}
params = urllib.urlencode(params)
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
conn = httplib.HTTPConnection(posturl)
conn.request("POST", "/xtts/servlet/kpl.tts.common.svl.SttSVL", params, headers)
response = conn.getresponse()
data = response.read()
conn.close()
 
try:
soup = BeautifulSoup.BeautifulSoup(data)
addressee = soup('table', {'class' : 'traceTable traceTableType02', 'summary' : '발송인/수취인 정보'})[0].tbody.findAll('tr')[1].td.string
statuslist = soup('table', {'class' : 'traceTable traceTableType02', 'summary' : '세부결과를 보여드립니다.'})[0].tbody.findAll('tr')
status = []
 
status.append({ 'type' : 'addressee',
'addressee' : addressee
})
 
for i in range(len(statuslist)):
if i == 1:
continue
else:
tdlist = statuslist[i].findAll('td')
if statuslist[i].get('id') == 'transport1' or statuslist[i].get('id') == 'transport2':
continue
# When Received
if len(tdlist) == 1:
statusreceiver = tdlist[0].string
status.append({ 'type' : 'recipient',
'recipient' : statusreceiver.strip()
})
else:
statusdate = tdlist[0].string
statustime = tdlist[1].string
statuslocation = tdlist[2].a.string
nowstatus = tdlist[3].string
statusdetail = tdlist[4].string
status.append({ 'type' : 'status',
'date' : statusdate,
'time' : statustime,
'location' : statuslocation,
'status' : nowstatus,
'detail' : statusdetail
})
 
for statusdata in status:
for key in statusdata.keys():
if statusdata[key]:
statusdata[key] = statusdata[key].strip()
 
return status
except IndexError:
return False
 
 
data = getpost('postnumber')
 
if not data:
print 'Invalid Number'
else:
for status in data:
if status['type'] is 'addressee':
print status['addressee']
if status['type'] is 'recipient':
print status['recipient']
if status['type'] is 'status':
print status['date']
print status['time']
print status['location']
print status['status']
print status['detail']


Leave a Comment