在房产数据应用开发中,获取精准的房源信息是关键。贝壳找房作为国内领先的房产平台,其数据接口为开发者提供了丰富的房源详情信息。本文将从技术角度分析如何调用贝壳找房的二手房详情API接口,并给出实际代码示例。
一、API接口基本结构
贝壳找房的二手房详情接口通常采用RESTful风格设计,通过HTTP GET请求获取数据。核心参数包括:
房源ID(house_id):唯一标识符
城市编码(city_code):定位城市区域
认证令牌(access_token):权限校验
典型请求URL格式示例:
https://api.ke.com/ershoufang/detail?house_id=101102345678&city_code=110000&access_token=xxxxxx
二、响应数据结构解析
成功调用接口后,返回的JSON数据通常包含以下关键字段:
{
"code": 200,
"message": "success",
"data": {
"basic": {
"title": "朝阳公园旁南北通透三居室",
"total_price": 850,
"unit_price": 78000,
"room": 3,
"hall": 2,
"area": 109.5,
"orientation": "南"
},
"position": {
"district": "朝阳区",
"community": "泛海国际",
"subway": "14号线东风北桥站800米"
},
"transaction": {
"listing_date": "2023-05-20",
"last_trade": "2020-08-15"
},
"images": [
{"url": "https://img1.ke.com/pic1.jpg", "type": "living_room"},
{"url": "https://img1.ke.com/pic2.jpg", "type": "bedroom"}
]
}
}
三、Python调用示例
使用requests库实现基础调用:
import requests
import json
def get_house_detail(house_id, city_code, access_token):
url = "https://api.ke.com/ershoufang/detail"
params = {
"house_id": house_id,
"city_code": city_code,
"access_token": access_token
}
try:
response = requests.get(url, params=params, timeout=10)
if response.status_code == 200:
data = json.loads(response.text)
if data.get('code') == 200:
return data['data']
else:
print(f"API错误: {data.get('message')}")
else:
print(f"HTTP错误: {response.status_code}")
except Exception as e:
print(f"请求异常: {str(e)}")
return None
示例调用
house_data = get_house_detail("101102345678", "110000", "your_token_here")
if house_data:
print(f"房源标题: {house_data['basic']['title']}")
print(f"总价: {house_data['basic']['total_price']}万")
四、关键技术要点
设置合理的请求间隔(建议≥3秒)
使用动态User-Agent头部
通过官方渠道申请合法access_token
使用Redis记录最后更新时间
redis_key = f"ke_house:{house_id}:last_update"
if not redis.exists(redis_key) or time.time() - float(redis.get(redis_key)) > 86400:
# 超过24小时更新数据
update_data(house_id)
捕获JSONDecodeError处理格式错误
监控429状态码(请求频次限制)
实现自动重试机制(带指数退避)
五、注意事项
严格遵守《数据安全法》和平台用户协议
敏感字段(如业主联系方式)需脱敏处理
建议使用官方SDK(若有提供)
大规模采集需提前联系平台开放平台部门
通过合理使用API接口,开发者可以构建基于实时房产数据的创新应用,但务必注意合规性和数据安全。建议定期检查接口变更,保持代码的持续适应性。