提升小间隔经纬度遍历循环速度 批量请求加拿大Circle K门店数据
解决方案
1. 遍历逻辑优化(解决重复请求+速度慢问题)
- 放弃全域等步长经纬度遍历方案,改用「先粗粒度扫面,再细粒度补漏」的策略:
- 第一步先用0.1的大步长遍历加拿大全境,记录每个坐标返回的门店覆盖边界,遇到返回门店数达到单页上限的区域,再缩小步长拆分该区域二次查询
- 直接使用加拿大行政区划的城市中心点坐标列表作为查询入口,加拿大全国活跃城市总数不超过200个,单城市查询覆盖周边10-20公里范围即可覆盖绝大多数门店,请求量直接从百万级降到百级
- 所有返回的门店数据用
门店唯一ID作为主键存入集合去重,自动过滤重复返回的相同门店
2. 分页数据批量拉取方案
该接口本身不支持一次性返回全部分页数据,你可以通过以下逻辑自动拉取指定坐标下的所有分页:
- 第一次请求
page=1,从返回结果中提取总门店数/总页数字段(通常接口返回会包含total、pages这类字段) - 循环请求
page=2到page=总页数的所有页面,汇总所有分页的门店数据 - 如果你找不到总页数标识,可以直接循环请求直到返回的门店列表为空时停止
3. 请求效率优化
- 用异步请求库
aiohttp替代同步的requests,并发请求可以把整体速度提升10-50倍,注意控制并发数在10-20之间避免被接口封禁IP - 可以检查接口是否支持
limit参数,调整单页返回的门店数量上限,减少分页请求次数
优化后的参考代码
import asyncio import aiohttp import json import numpy as np from collections import OrderedDict # 去重存储,用门店id作为key自动去重 stores = OrderedDict() # 请求头复用 HEADERS = { 'Connection': 'keep-alive', 'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"', 'Accept': '*/*', 'X-Requested-With': 'XMLHttpRequest', 'sec-ch-ua-mobile': '?0', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36', 'Sec-Fetch-Site': 'same-origin', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Dest': 'empty', 'Referer': 'https://www.circlek.com/store-locator?Canada&lat=43.6529&lng=-79.3849', 'Accept-Language': 'en-GB,en-US;q=0.9,en;q=0.8', 'dnt': '1' } async def fetch_stores(session, lat, lng, page=1): url = f"https://www.circlek.com/stores_new.php?lat={lat}&lng={lng}&services=®ion=global&page={page}" try: async with session.get(url, headers=HEADERS, timeout=10) as resp: if resp.status != 200: return [] data = await resp.json() # 假设返回的门店列表在data['stores']字段,根据实际返回结构调整 store_list = data.get('stores', []) for store in store_list: # 假设门店唯一id字段为store_id,根据实际返回结构调整 store_id = store.get('store_id') if store_id and store_id not in stores: stores[store_id] = store return store_list except Exception as e: print(f"请求失败 lat:{lat} lng:{lng} page:{page} 错误:{str(e)}") return [] async def fetch_all_pages_for_point(session, lat, lng): page = 1 while True: current_page_stores = await fetch_stores(session, lat, lng, page) if not current_page_stores: break page += 1 # 防止接口无限返回相同内容,设置最大页数限制 if page > 50: break async def main(): # 粗粒度坐标列表,可替换为加拿大城市中心点列表 lat_lng = [(lat, long) for lat, long in zip(np.arange(42, 84, 0.1), np.arange(-142, -52, 0.1))] # 控制并发数为10 connector = aiohttp.TCPConnector(limit=10) async with aiohttp.ClientSession(connector=connector) as session: tasks = [fetch_all_pages_for_point(session, lat, lng) for lat, lng in lat_lng] await asyncio.gather(*tasks) # 输出所有去重后的门店数据 print(json.dumps(list(stores.values()), ensure_ascii=False, indent=2)) if __name__ == "__main__": asyncio.run(main())
内容的提问来源于stack exchange,提问作者John_Muir
相关产品推荐
相关产品推荐

