python透過IP獲取國家和城市地市的方法

lytcreate發表於2024-11-09

程式碼如下:

import geoip2.database
def get_city_info(ip_address):
    reader = geoip2.database.Reader('C:\\Users\lytcreate\Downloads\\222\GeoLite2-City.mmdb')
    try:
        response = reader.city(ip_address)
        print(response.city.names.get('zh-CN'))
        city_name = response.city.name
        country_name = response.country.name
        print(f"城市:{city_name},國家:{country_name}")
    except geoip2.errors.AddressNotFoundError:
        print("未找到該IP地址對應的地理位置資訊")
    finally:
        reader.close()


if __name__ == '__main__':
    ip = "113.132.182.74"
    get_city_info(ip)

相關文章