使用Requests爬取超市API返回异常:促销信息缺失
问题:请求超市API获取的促销信息与网页Network中显示不一致
我用Python的requests库开发了一段代码,调用超市API获取商品信息,其他字段都能正常返回,但response['items'][1]['promotions']始终返回空列表。但网页的Network→Response标签中,该字段明明包含促销数据,直接访问请求URL也无法获取到预期的促销信息。
代码示例
import requests import numpy as np def fetch_data(base_url): params = { 'take': 30, 'skip': 0, 'page': 1 } headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36 Edg/112.0.1722.64', 'Accept': 'application/json, text/plain, */*', 'Accept-Language': 'en-US,en;q=0.9', 'Origin': 'https://shop.supervalu.ie', 'Referer': 'https://shop.supervalu.ie', 'X-Site-Host': 'https://shop.supervalu.ie', } with requests.Session() as s: # Initial request to get the entire product response response = s.get( base_url, params=params, headers=headers ).json() product_name = response['items'][1]['name'] print(product_name) #Prints 'SuperValu Large Loose Oranges (1 Piece)' print(response['items'][1]['promotions']) #List comes back empty? #deal = response['items'][1]['promotions']['name'] #print(deal) fetch_data('https://storefrontgateway.supervalu.ie/api/stores/5550/categories/O200001/search?')
预期的promotions数据
"promotions": [
{
"id": "11PR3969",
"name": "2 for €5",
"description": "2 for €5",
"additionalInformation": "SuperValu Fruit",
"startDate": "02/11/2023",
"endDate": "31/12/2049",
"limit": 0,
"threshold": null,
"minimumQuantity": 2,
"pointsBased": false,
"imageUrl": null,
"limitPerSku": null
}
]
排查方向与解决方法
- 核对请求参数:打开浏览器Network的Request面板,对比代码中的
params和浏览器实际发送的参数,可能缺少storeId、region这类和门店/地域相关的参数,补上后重试。 - 补全请求头信息:重点检查
Cookie、Authorization这类会话相关的头,网页在访问过程中会生成会话标识,服务器依赖这些信息返回个性化的促销数据。可以把浏览器中的Cookie完整复制到headers中测试。 - 确认请求方式:检查浏览器发起请求时用的是GET还是POST,是否有额外的请求体参数。如果是POST,需要调整代码用post方法并传入对应的请求体。
- 模拟完整会话流程:网页加载商品页前可能有前置请求(比如初始化会话、获取门店配置),先用Session访问商品首页,再请求目标API,让Session自动保存必要的Cookie和会话状态。
- 检查是否有独立促销接口:部分网站的促销信息是通过单独的API返回,再由前端拼接显示。可以在Network中搜索包含"promotion"关键词的请求,找到对应接口单独调用获取数据。
内容的提问来源于stack exchange,提问作者Oxin
相关产品推荐
相关产品推荐

