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

如何使用Python获取IP地址的地理位置(网站用户场景)

基于IP获取地理位置的Python实现方案

你的现有代码问题

你当前用Selenium的方法存在两个核心问题:

  • 该网页获取的是运行浏览器的服务器/本地的地理位置,不是你传入的目标IP对应的位置,完全没用到参数ip
  • 用浏览器渲染页面的方式效率极低,不适合网站后端服务场景

推荐实现方法

方法1:使用本地IP数据库(推荐,无API依赖)

可以用geoip2库配合MaxMind的免费IP数据库,不需要调用外部接口,速度快且稳定。

步骤:

  1. 安装依赖库:
pip install geoip2
  1. 下载MaxMind免费的GeoLite2 Country数据库(需注册后获取)
  2. 编写代码:
import geoip2.database

def get_country_by_ip(ip):
    # 替换为你的GeoLite2-Country.mmdb文件路径
    reader = geoip2.database.Reader('GeoLite2-Country.mmdb')
    try:
        response = reader.country(ip)
        # 获取中文国家名称(若不存在则用英文)或国家代码
        country_name = response.country.names.get('zh-CN', response.country.name)
        country_code = response.country.iso_code
        return {'country_name': country_name, 'country_code': country_code}
    except geoip2.errors.AddressNotFoundError:
        return {'error': '该IP地址无法查询到地理位置'}
    finally:
        reader.close()

# 调用示例
result = get_country_by_ip('8.8.8.8')
print(result)

方法2:调用IP查询API(轻量,无需本地数据库)

如果不想维护本地数据库,可以用免费的IP查询API,直接通过HTTP请求获取结果:

import requests

def get_country_by_ip(ip):
    try:
        # 替换为合规的IP查询API地址
        response = requests.get(f"https://[IP查询API域名]/ip/{ip}", timeout=5)
        data = response.json()
        # 根据API返回的JSON结构提取国家信息
        country_name = data.get('country', '')
        country_code = data.get('country_code', '')
        return {'country_name': country_name, 'country_code': country_code}
    except requests.exceptions.RequestException:
        return {'error': '查询失败'}

# 调用示例
result = get_country_by_ip('8.8.8.8')
print(result)

注意事项

  • 本地数据库需要定期更新,保证IP数据的准确性
  • 免费API通常有请求次数限制,适合小流量场景;大流量建议用本地数据库或付费API
  • 处理用户IP时要注意合规,遵守隐私相关法规

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 00:37:42