目录
[python-amap-rental结合高德 API 和 Python 解决租房问题的脚本](#python-amap-rental结合高德 API 和 Python 解决租房问题的脚本)
[get_geocode 函数:](#get_geocode 函数:)
[search_rentals 函数:](#search_rentals 函数:)
Python实例题
题目
高德API+Python解决租房问题
python-amap-rental结合高德 API 和 Python 解决租房问题的脚本
python
import requests
import json
# 替换为你自己的高德 API Key
AMAP_API_KEY = "your_amap_api_key"
def get_geocode(address):
"""
通过高德地理编码 API 获取地址的经纬度
:param address: 要查询的地址
:return: 经纬度字符串,格式为 "经度,纬度"
"""
url = f"https://restapi.amap.com/v3/geocode/geo?key={AMAP_API_KEY}&address={address}"
try:
response = requests.get(url)
response.raise_for_status()
data = response.json()
if data["status"] == "1" and data["geocodes"]:
location = data["geocodes"][0]["location"]
return location
else:
print("未获取到有效的经纬度信息。")
return None
except requests.RequestException as e:
print(f"请求出错: {e}")
return None
def search_rentals(location, radius=3000):
"""
通过高德周边搜索 API 查找指定位置附近的租房信息
:param location: 经纬度字符串,格式为 "经度,纬度"
:param radius: 搜索半径,单位为米,默认为 3000 米
:return: 租房信息列表
"""
url = f"https://restapi.amap.com/v3/place/around?key={AMAP_API_KEY}&location={location}&keywords=租房&radius={radius}&types=120302&output=json"
try:
response = requests.get(url)
response.raise_for_status()
data = response.json()
if data["status"] == "1" and data["pois"]:
rentals = []
for poi in data["pois"]:
rental = {
"name": poi["name"],
"address": poi["address"],
"distance": poi["distance"]
}
rentals.append(rental)
return rentals
else:
print("未找到附近的租房信息。")
return []
except requests.RequestException as e:
print(f"请求出错: {e}")
return []
if __name__ == "__main__":
work_address = input("请输入你的工作地点: ")
location = get_geocode(work_address)
if location:
rentals = search_rentals(location)
if rentals:
print("以下是附近的租房信息:")
for rental in rentals:
print(f"名称: {rental['name']}, 地址: {rental['address']}, 距离: {rental['distance']} 米")
代码解释
get_geocode
函数:
- 构建地理编码 API 的请求 URL,将用户输入的地址作为参数。
- 发送 HTTP 请求,若请求成功且返回有效数据,提取经纬度信息并返回。
- 处理请求异常和数据无效的情况。
search_rentals
函数:
- 构建周边搜索 API 的请求 URL,将经纬度和搜索半径作为参数。
- 发送 HTTP 请求,若请求成功且返回有效数据,提取租房的名称、地址和距离信息,存储在列表中返回。
- 处理请求异常和未找到租房信息的情况。
主程序:
- 提示用户输入工作地点。
- 调用
get_geocode
函数获取工作地点的经纬度。 - 若获取到经纬度,调用
search_rentals
函数查找附近的租房信息并打印。
运行思路
- 获取高德 API Key :前往高德开放平台(高德开放平台 | 高德地图API )注册账号,创建应用,获取 API Key。
- 安装依赖库 :确保已经安装了
requests
库,若未安装,可使用以下命令进行安装:
python
pip install requests
- 修改代码 :将代码中的
AMAP_API_KEY
替换为你自己的 API Key。 - 运行脚本 :将上述代码保存为
amap_rental_search.py
文件,在终端中运行:
python
python amap_rental_search.py
- 输入信息:按照提示输入工作地点。
- 查看结果:程序会打印出附近的租房信息。
注意事项
- API 限制:高德 API 有调用频率限制,若需要大量查询,可考虑申请更高的配额。
- 数据准确性:周边搜索 API 返回的租房信息可能不够全面或准确,可结合其他租房平台进一步查找。
- 费用问题:若使用 API 的频率较高,可能会产生一定的费用,需关注高德开放平台的收费标准。