Python请求Shopify智能集合分页参数报错问题解决
解决Shopify智能集合分页获取所有数据的问题
Shopify的REST API已不再推荐使用page参数进行分页(这也是你使用page参数报错的核心原因),官方推荐的是基于cursor的分页机制——通过after参数定位下一页数据的起始位置,能稳定获取超过250条的智能集合数据。
核心实现思路
- 单页请求设置
limit=250(Shopify允许的单页最大返回数量) - 每次请求后,从响应体的
page_info.next_page_info字段获取下一页的cursor标记 - 循环发起请求,直到没有下一页的cursor为止
Python代码示例
import requests # 配置你的店铺信息和API凭证 SHOP_DOMAIN = "your-shop-name.myshopify.com" API_VERSION = "2024-07" # 使用Shopify最新稳定API版本 ACCESS_TOKEN = "your-access-token" base_url = f"https://{SHOP_DOMAIN}/admin/api/{API_VERSION}/smart_collections.json" headers = {"X-Shopify-Access-Token": ACCESS_TOKEN} all_smart_collections = [] params = {"limit": 250} # 单页拉取最大数量 while True: # 发送请求 response = requests.get(base_url, headers=headers, params=params) response.raise_for_status() # 抛出请求错误,便于调试 data = response.json() # 收集当前页的智能集合 current_page_collections = data["smart_collections"] all_smart_collections.extend(current_page_collections) print(f"已获取 {len(all_smart_collections)} 个智能集合") # 获取下一页的cursor标记 next_page_info = data.get("page_info", {}).get("next_page_info") if not next_page_info: break # 无下一页数据,终止循环 # 更新请求参数,添加after标记 params["after"] = next_page_info # 处理最终获取的所有集合 print(f"共获取 {len(all_smart_collections)} 个智能集合")
补充说明
- 若使用的API版本较旧,响应体中无
page_info字段,可解析响应头的Link字段提取after参数:from urllib.parse import urlparse, parse_qs link_header = response.headers.get("Link") next_page_info = None if link_header: for link in link_header.split(","): if 'rel="next"' in link: next_url = link.split(";")[0].strip("<>") query_params = parse_qs(urlparse(next_url).query) next_page_info = query_params.get("after", [None])[0] break - 务必使用Shopify当前支持的稳定API版本,旧版本可能存在分页逻辑差异
- 注意Shopify的API速率限制,可在循环中添加
time.sleep(1)避免触发限制
内容的提问来源于stack exchange,提问作者Alex Co
相关产品推荐
相关产品推荐

