Python 高德地图POI信息爬取代码详解

本文介绍了如何使用Python编写函数get_amap_poi从高德地图获取指定城市的POI信息,通过API密钥进行参数设置并进行分页查询,同时附有注意事项和API使用规则。
该文章已生成可运行项目,

1. 函数要点整理

get_amap_poi(city, keywords, page)

这个函数旨在从高德地图中提取指定城市的POI(Point of Interest)信息。以下是函数的参数和返回值说明:

  • 参数:

    • city: 城市名称,指定要搜索的城市。
    • keywords: 关键词,用于过滤POI,例如"公交站"。
    • page: 返回POI的页码数,用于分页获取结果。
  • 返回值:

    • 包含POI信息的列表。

2. 代码实现思路

  1. 构建高德地图Web API请求的URL。
  2. 替换api_key为你的高德地图Web API密钥。
  3. 定义请求参数,包括key(API密钥)、keywordsoffset(偏移量)、page(页码数)、city(城市名称)、output(输出格式为json)。
  4. 使用requests.get发起GET请求。
  5. 解析响应,提取POI信息。

3. 整体代码(附加注释)

import requests

def get_amap_poi(city, keywords, page):
    """
    获取高德地图上指定城市的POI信息
    :param page: 返回poi的页码数
    :param city: 城市名称
    :param keywords: 关键词,例如"公交站"
    :return: POI信息的列表
    """
    amap_api_url = "https://restapi.amap.com/v3/place/text"

    # 替换为你的高德地图Web API Key
    api_key = "YOUR_WEB_API_KEY"

    # 请求参数
    params = {
        "key": api_key,
        "keywords": keywords,
        "offset": 1000,
        "page": page,
        "city": city,
        "output": "json"
    }

    # 发起请求
    response = requests.get(amap_api_url, params=params)
    result = response.json()

    # 提取POI信息
    if result["status"] == "1" and int(result["count"]) > 0:
        pois = result["pois"]
        return pois
    else:
        print("未找到符合条件的POI信息")
        return []

def main():
    city_name = "武汉市"  # 替换为目标城市
    keyword = "高等院校"
    page_num = 1

    pois = get_amap_poi(city_name, keyword, page_num)
    output_label = ['name', 'location', 'tel', 'pname', 'cityname', 'adname', 'address']

    if pois:
        for poi in pois:
            info = []
            for label in output_label:
                info.append(poi[label])
            print(info)
    else:
        print("未找到符合条件的POI信息")

if __name__ == "__main__":
    main()

4. 注意事项

  • API密钥替换:api_key替换为你在高德地图开放平台注册应用后获得的API密钥
  • 城市名称:main函数中,将city_name替换为你希望搜索的城市名称或城市编码
  • 关键词:main函数中,将keyword替换为你希望搜索的关键词,例如"学校"、"医院"等。
  • 输出字段: output_label定义了输出的字段,可以根据需要进行调整。确保这些字段在API返回的POI信息中存在。
  • 编码表链接: 高德Web服务 API 相关POI编码与城市编码

以上代码可用于爬取高德地图上指定城市的特定关键词POI信息。在使用时,请遵循高德地图API的使用规定,特别是保护个人信息和防止滥用API。


术语解释表格:

术语解释
POIPoint of Interest,地理位置上感兴趣的点,如学校、医院等。
APIApplication Programming Interface,应用程序编程接口,用于不同软件系统间的通信。
JSONJavaScript Object Notation,一种数据交换格式。

如果这对您有所帮助,希望点赞支持一下作者! 😊

点击查看原文

file

本文章已经生成可运行项目
### Python 高德地图 POI 数据爬取并判断网络类型 以下是实现通过 `Python` 爬取高德地图 POI 数据的代码示例,同时加入了对当前网络类型的判断逻辑(本网/异网)。此代码基于 `requests` 和 `json` 库完成。 #### 1. 导入必要的库 ```python import requests import json from urllib.parse import urlencode ``` #### 2. 定义函数用于发送请求 定义一个通用函数来处理 API 请求,并解析返回的结果。 ```python def fetch_poi_data(api_key, polygon, keywords=None, types=None, extensions="base"): """ 发送请求到高德地图API获取POI数据 参数: api_key (str): 高德开发者平台申请的API Key. polygon (str): 多边形区域字符串,格式为"lng,lat|lng,lat|..." keywords (str): 关键词过滤条件,默认为空表示不限制关键词. types (str): 类型筛选参数,默认为空表示不限制类型. extensions (str): 返回结果详略程度选项:"base"/"all". 返回: dict: 解析后的JSON响应对象. """ base_url = "https://restapi.amap.com/v3/place/polygon" params = { 'key': api_key, 'polygon': polygon, 'extensions': extensions, 'offset': 25, # 单次最大数量限制 'page': 1 # 起始页码 } if keywords is not None: params['keywords'] = keywords if types is not None: params['types'] = types url = f"{base_url}?{urlencode(params)}" response = requests.get(url) data = response.json() return data ``` #### 3. 实现递归网格划分功能 如果某个区域内 POI 数量超过阈值,则进一步细分该区域。 ```python def recursive_fetch(api_key, polygons_list, result_container): new_polygons = [] for poly in polygons_list: res = fetch_poi_data(api_key=api_key, polygon=poly)[^1] total_count = int(res.get('count', 0)) if total_count > 850: sub_polys = split_polygon_into_four(poly) # 假设有一个方法可以四分多边形 new_polygons.extend(sub_polys) else: pois = res.get('pois', []) result_container.extend(pois) if new_polygons: recursive_fetch(api_key, new_polygons, result_container) ``` #### 4. 添加网络类型检测模块 利用 `socket` 或其他工具简单区分本地局域网还是外部互联网连接状态。 ```python import socket def detect_network_type(): try: hostname = socket.gethostname() ip_address = socket.gethostbyname(hostname) local_ips = ['127.', '192.168.'] # 局域网常见IP前缀列表 for prefix in local_ips: if ip_address.startswith(prefix): return "Local Network" return "External Internet" except Exception as e: return str(e) ``` #### 5. 主程序入口 将以上各部分组合起来形成完整的解决方案。 ```python if __name__ == "__main__": amap_api_key = "<Your_AMap_API_Key>" initial_polygon = "116.368344,39.914030|116.377422,39.914030|116.377422,39.922285|116.368344,39.922285" all_results = [] network_status = detect_network_type() print(f"Current Network Type Detected As:{network_status}") if network_status != "Error": recursive_fetch(amap_api_key, [initial_polygon], all_results) with open("amap_poi_output.json", mode='w') as output_file: json.dump(all_results, output_file, ensure_ascii=False, indent=4) print("Data successfully saved to file.") ``` --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值