循环调用房产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
相关产品推荐
相关产品推荐

