python通过IP获取国家和城市地市的方法
代码如下:
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)