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

循环调用房产API时重置Offset变量的技术问题

解决Realty Mole API多邮编遍历的Offset重置问题

你的代码核心问题是offset变量在全局初始化,第一个邮编的循环结束后,offset会累积到较大数值(比如5500),处理第二个邮编时未重置该值,直接从这个大offset开始请求,而目标邮编的房源总数可能不足这个偏移量,导致无法获取数据。

修改方案

将offset的初始化逻辑放到每个邮编的循环开头,确保处理新邮编时,offset从你需要的初始值(按你的需求设为500,若API要求从0开始取第一页则改为0)重新累加。

修改后的代码

# This just formats your token for the requests library.
headers = {
"X-RapidAPI-Key": "your-key-here",
"X-RapidAPI-Host": "realty-mole-property-api.p.rapidapi.com"
}

# Initial Limit value.
limit = 500
zipCode = [77449, 77008]

# This will be an array of all the listing records.
texas_listings = []

# We loop until we get no results.
for i in zipCode:
    # 每个邮编处理前重置offset为初始值
    offset = 500
    while True:
        print("----")
        url = f"https://realty-mole-property-api.p.rapidapi.com/rentalListings?offset={offset}&limit={limit}&zipCode={i}"
        print("Requesting", url)
        response = requests.get(url, headers=headers)
        data = response.json()
        print(data)
        # Did we find any listings?
        if len(data) == 0:
            # If not, exit the loop
            break

        # If we did find listings, add them to the data
        # and then move onto the next offset.
        texas_listings.extend(data)

        offset = offset + 500

补充说明

如果Realty Mole API的offset参数是从0开始计数(即offset=0对应第一页数据),建议将初始offset设为0,避免跳过目标邮编的前500条房源,可根据API文档实际规则调整初始值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 04:35:46