1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

郵便番号から住所を取得する

Posted at

郵便番号から住所を特定したい時に使う

郵便局の地域検索を利用
https://www.post.japanpost.jp/zipcode/index.html

上記フォームの結果をパースして戻り値をdictionaryで返すfunction

import requests
from bs4 import BeautifulSoup
import re


pref_key = {
    '北海道': 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
}


def get_html_text(url: str) -> str:
    try:
        req = requests.get(url)
    except requests.exceptions.ConnectionError:
        return False
    return req.content


def getAddress(postal_code: int) -> dict:
    url = f'https://www.post.japanpost.jp/smt-zipcode/zipcode.php?zip={postal_code}'
    content = get_html_text(url)
    if not content:
        return False
    soup = BeautifulSoup(content, 'html.parser')
    dds = [i.text.strip() for i in soup.body.findAll('dd')]
    if not dds:
        return False
    dds = dds[:4]
    info = {
        'postal': dds[0].replace('-', ''),
        'pref': dds[1],
        'city': dds[2],
        'address': re.sub(r'\(.*', '', dds[3])
    }
    info['pref_no'] = pref_key[info['pref']]
    return info


if __name__ == "__main__":
    data = getAddress(1000004)
    print(data)

"""
結果
{
  'postal': '1000004', 
  'pref': '東京都', 
  'city': '千代田区', 
  'address': '大手町(次のビルを除く・JAビル)', 
  'pref_no': 13
}
""" 
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?