代码之家  ›  专栏  ›  技术社区  ›  AhmedGalal s

如何使用python从windows获取位置

  •  0
  • AhmedGalal s  · 技术社区  · 2 年前

    我想从窗口获取位置

    我试图使用ipinfo.io从IP获取位置,但信息无效,所以我想从windows获取位置

    我只想知道如何定位 我在网上没有找到任何东西

    1 回复  |  直到 2 年前
        1
  •  0
  •   KuLeMi    2 年前

    这对我有用

    import requests
    
    def get_global_ip():
        try:
            response = requests.get('https://ipinfo.io/json')
            data = response.json()
            return data['ip'], data['country'], data['city']
        except Exception as e:
            print("Error while retrieving location:", e)
            return None
    
    global_ip = get_global_ip()
    if global_ip:
        print("Your global IP address and location:", global_ip)
    else:
        print("Failed to retrieve the global IP address and location")
    

    或者,如果你知道你的ip,你可以试试这个:

    import requests
    
    def get_location(ip):
        url = f"http://ip-api.com/json/{ip}"
        response = requests.get(url)
        data = response.json()
        if data['status'] == 'success':
            return data['city'], data['country']
        else:
            return None
    
    my_ip = 'xxx.xxx.xxx.xxx' # global/white ip-address
    
    location = get_location(my_ip)
    if location:
        city, country = location
        print(f"Your city: {city}, country: {country}")
    else:
        print("It is not possible to get info about your location :(")