摘要:本文详细介绍如何通过电商平台开放的API接口获取商品详情H5页面数据,涵盖淘宝/天猫、京东两大平台的实现方法,并提供Python代码示例。内容包含接口权限申请、请求参数构建、数据解析及常见问题处理,适用于电商数据采集、价格监控等场景。
1. 接口类型与适用场景
商品详情H5接口主要分为两类:
-
官方开放平台API:通过淘宝/京东开放平台申请,数据规范且稳定(如
taobao.item_get
、jd.item_get_app
) -
H5页面解析接口:直接请求移动端H5页面接口,需处理反爬机制(如
mtop.taobao.detail.getdetail
)
典型应用场景:
-
价格监控系统
-
商品信息聚合展示
-
竞品数据分析
-
库存预警系统
2. 接口权限申请流程
淘宝/天猫开放平台
-
注册账号并完成企业认证
-
创建应用,选择“网站应用”或“服务器应用”
-
申请
taobao.item_get
接口权限 -
获取
App Key
和App Secret
京东开放平台
-
登录京东宙斯开放平台
-
创建应用并绑定类目
-
申请
jd.item_get_app
接口权限 -
获取
access_token
3. 淘宝/天猫接口实现
方法一:官方API调用(推荐)
import requests
import hashlib
import time
class TaobaoAPI:
def __init__(self, app_key, app_secret):
self.app_key = app_key
self.app_secret = app_secret
self.endpoint = "https://eco.taobao.com/router/rest"
def _generate_sign(self, params):
"""生成API签名"""
sorted_params = sorted(params.items())
base_str = self.app_secret + ''.join([f'{k}{v}' for k, v in sorted_params]) + self.app_secret
return hashlib.md5(base_str.encode()).hexdigest().upper()
def get_item_detail(self, item_id):
params = {
"method": "taobao.item.get",
"app_key": self.app_key,
"timestamp": str(int(time.time())),
"format": "json",
"v": "2.0",
"sign_method": "md5",
"item_id": item_id,
"fields": "title,price,pic_url,sku,stock"
}
params["sign"] = self._generate_sign(params)
try:
response = requests.get(self.endpoint, params=params)
data = response.json()
return data.get('item_get_response', {}).get('item', {})
except Exception as e:
print(f"API请求失败: {str(e)}")
return None
# 使用示例
if __name__ == "__main__":
api = TaobaoAPI("YOUR_APP_KEY", "YOUR_APP_SECRET")
item_data = api.get_item_detail("627831423578")
print(item_data)
方法二:H5页面接口调用(需处理反爬)
import requests
import json
def get_taobao_h5_data(item_id):
url = "https://h5api.m.taobao.com/h5/mtop.taobao.detail.getdetail/6.0/"
headers = {
'User-Agent': 'Mozilla/5.0 (Linux; Android 10) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.120 Mobile Safari/537.36',
'Referer': f'https://detail.m.tmall.com/item.htm?id={item_id}'
}
payload = {
'data': f'{{"itemNumId":"{item_id}"}}',
'api': 'mtop.taobao.detail.getdetail',
'v': '6.0',
'appKey': '12574478'
}
response = requests.post(url, headers=headers, data=payload)
if response.status_code == 200:
return response.json().get('data', {}).get('item', {})
return None
# 调用示例
item_info = get_taobao_h5_data("627831423578")
print(item_info['title'], item_info['price'])
4. 京东接口实现
import requests
def get_jd_item_detail(item_id, api_key, api_secret):
url = "https://api.jd.com/routerjson"
params = {
"method": "jd.union.open.goods.detail.query",
"app_key": api_key,
"access_token": "YOUR_ACCESS_TOKEN",
"timestamp": str(int(time.time())),
"v": "1.0",
"skuIds": item_id,
"sign": self._generate_jd_sign(params) # 需实现京东签名算法
}
response = requests.get(url, params=params)
return response.json().get('data', [])
# 响应数据结构示例
"""
{
"skuId": "100000000001",
"skuName": "商品名称",
"price": "599.00",
"imageList": ["http://img14.360buyimg.com/...jpg"],
"stock": 1000
}
"""
5. 数据解析与存储
数据解析示例
def parse_taobao_item(data):
return {
"title": data.get("title"),
"price": data.get("price"),
"images": [img['url'] for img in data.get('item_imgs', [])],
"sku": [f"{prop['name']}:{value['name']}"
for prop in data.get('props', [])]
}
# 存储至MySQL
import mysql.connector
def save_to_db(item_data):
conn = mysql.connector.connect(
host='localhost', user='root', password='123456', database='items'
)
cursor = conn.cursor()
sql = "INSERT INTO products (title, price) VALUES (%s, %s)"
cursor.execute(sql, (item_data['title'], item_data['price']))
conn.commit()
6. 注意事项与优化建议
-
频率限制:
-
淘宝默认5000次/天,超限会导致IP封禁1
-
京东根据API等级限制调用次数6
-
-
反爬策略:
-
使用随机User-Agent和代理IP池
-
添加请求间隔(建议≥2秒)7
-
-
数据合规:
-
遵守《电商平台数据使用协议》
-
敏感数据加密存储39
-
-
错误处理:
try: response = requests.get(url, timeout=10) response.raise_for_status() except requests.exceptions.HTTPError as err: print(f"HTTP错误: {err}") except requests.exceptions.Timeout: print("请求超时")
7. 接口试用