如何使用python从Windows获取位置

问题描述 投票:0回答:1

我想从 Windows 获取位置

我尝试使用 ipinfo.io 从 IP 获取定位信息,但信息无效,所以我想从 Windows 获取定位信息

我只想如何获取位置 我在网上没有找到任何东西

python json python-3.x windows python-3.8
1个回答
0
投票

这对我有用

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 :(")

© www.soinside.com 2019 - 2024. All rights reserved.