Python 高德地图POI信息爬取代码判断本网异网
时间: 2025-06-06 09:20:37 浏览: 22
### 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.")
```
---
###
阅读全文
相关推荐

















