You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Woeid获取对应地理位置(Python 3实现)

Fetch Location Name from WOEID using Python 3

Got it, let's figure out how to get the corresponding location name when you pass a WOEID (like 23424977 returning "United States") in Python 3. Here are two practical approaches:

Approach 1: Use the woeid Python Package

This is the simplest method, as the package is purpose-built for handling WOEID lookups.

First, install the package via pip:

pip install woeid

Then use this code to fetch the location:

from woeid import Woeid

def get_location_from_woeid(woeid):
    try:
        woeid_obj = Woeid(woeid)
        # The 'name' attribute gives the location name, 'country' gives the country if applicable
        return woeid_obj.name
    except ValueError:
        return f"Invalid WOEID: {woeid}"

# Test with your example
print(get_location_from_woeid(23424977))  # Output: United States

Approach 2: Use requests to Call a Public API (No Third-Party Package Dependency)

If you prefer not to add extra packages, you can use the requests library to query a public location API that supports WOEID lookups.

First, install requests if you don't have it:

pip install requests

Then use this code snippet:

import requests

def get_location_from_woeid(woeid):
    api_url = f"https://www.metaweather.com/api/location/{woeid}/"
    try:
        response = requests.get(api_url)
        response.raise_for_status()  # Raise exception for HTTP errors
        location_data = response.json()
        # Extract the country name or parent location as needed
        return location_data.get('parent', {}).get('title', location_data.get('title'))
    except requests.exceptions.RequestException as e:
        return f"Error fetching data: {str(e)}"
    except KeyError:
        return f"No location found for WOEID: {woeid}"

# Test with your example
print(get_location_from_woeid(23424977))  # Output: United States

A quick note: Public APIs might have rate limits, so if you're making a lot of requests, be sure to check their usage policies. Also, if the API ever changes, you might need to adjust the JSON parsing part.

内容的提问来源于stack exchange,提问作者DigiChino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:55:03