郵局提供了 web service 方便 大量且快速查詢郵遞區號。
注意:要申請!要申請!要申請!
1. 開放 個人/團體/企業 申請,但要有固定 IP。
2. 要填寫 web service 系統介接申請書,郵局才會將貴公司 IP 列入白名單,貴公司的查詢程式才能正常運作。
#!/usr/bin/python
#-*- coding:utf-8 -*-
import requests
import xml.etree.cElementTree as ET
...
...
def main():
# sAddr = '高雄市前金區'
# sAddr = '高雄市前金區光復一街'
sAddr = '完整的地址'
sZip = GetZip(sAddr) # 正式
# sZip = GetZip(sAddr,0) # 測試
if(sZip is None):
print('查詢失敗')
else:
print('sZip = '+sZip)
# 郵局 web service, 取得 3+3 郵遞區號
# 傳入的參數 bTest: 執行函數的模式, 預設為 "正式"=1, 若為 0 時, 則列出傳回的各節點(node) 內容
def GetZip(ss, bTest=1):
mydata = (''
'<soap12:envelope xmlns:soap12="http://www.w3.org/2003/05/soap-envelope" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
'<soap12:body>'
'<getzipcode xmlns="http://tempuri.org/">'
'<addrstr>' + ss + '</addrstr>'
'</getzipcode>'
'</soap12:body>'
'</soap12:envelope>')
url = 'http://33wsp.post.gov.tw/lzwzip/tzip33.asmx'
headers = {'content-type': 'application/soap+xml'}
response = requests.post(url,data=mydata,headers=headers)
root = ET.fromstring(response.content)
sResult = None
for child in root.iter('*'):
if(bTest==0):
print(child.tag, child.text)
if (child.tag=='{http://tempuri.org/}GetZipCodeResult'):
if(child.text is None):
pass
else:
if(len(child.text)==6):
sResult = child.text
break
return sResult
# 當地址不完整時, 傳回的值為空值 None
('{http://www.w3.org/2003/05/soap-envelope}Envelope', None)
('{http://www.w3.org/2003/05/soap-envelope}Body', None)
('{http://tempuri.org/}GetZipCodeResponse', None)
('{http://tempuri.org/}address', None)
# 當地址完整時
('{http://www.w3.org/2003/05/soap-envelope}Envelope', None)
('{http://www.w3.org/2003/05/soap-envelope}Body', None)
('{http://tempuri.org/}GetZipCodeResponse', None)
('{http://tempuri.org/}GetZipCodeResult', '801002') # 當有資料成功傳回時, 郵遞區號在這
2022.06.25 測試,之前還會有傳回 3 碼郵區的情況,現在好像只會傳回 None 或 6 碼郵區。
當地址內含有 路/街... 等,即使沒有門牌號碼,郵局 web service 就可能傳回 6 碼郵區,例如:"高雄市前金區光復一街",因此 並不能將 web service 做為判別地址完整性的方法。
沒有留言:
張貼留言