Amazon(亚马逊)开放平台的item_search接口是通过关键词搜索商品列表的核心工具,适用于全球跨境电商选品、市场分析、价格监控等场景。作为全球最大的电商平台,其商品数据覆盖范围广、商业价值高。本文将全面讲解该接口的对接流程、参数配置、代码实现及最佳实践,帮助开发者系统掌握从入门到精通的全流程。
一、接口基础认知
二、对接前置准备
三、接口调用流程
四、代码实现示例(Python)
import requests
import datetime
import xmltodict
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
class AmazonSearchApi:
def __init__(self, access_key, secret_key, associate_tag, region="com"):
self.access_key = access_key
self.secret_key = secret_key
self.associate_tag = associate_tag
self.region = region # 区域:com/co.uk/de/co.jp等
self.host = f"webservices.amazon.{region}"
self.endpoint = f"https://{self.host}/onca/xml"
self.service = "AWSECommerceService"
def generate_signed_url(self, params):
"""生成带V4签名的请求URL"""
# 组装基础参数
base_params = {
"Service": self.service,
"AWSAccessKeyId": self.access_key,
"AssociateTag": self.associate_tag,
"Timestamp": datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ'),
"Operation": "ItemSearch"
}
base_params.update(params)
# 构建AWS请求并签名
request = AWSRequest(
method="GET",
url=self.endpoint,
params=base_params
)
sigv4 = SigV4Auth(
credentials={
'access_key': self.access_key,
'secret_key': self.secret_key
},
service_name=self.service,
region_name=self.region
)
sigv4.add_auth(request)
return request.url
def parse_response(self, xml_content):
"""解析XML响应为字典"""
try:
return xmltodict.parse(xml_content, dict_constructor=dict)
except Exception as e:
return {"error": f"XML解析错误: {str(e)}"}
def item_search(self, keywords, search_index="All", page=1, sort=None, response_group="ItemAttributes,Offers,Images"):
"""
搜索商品列表
:param keywords: 搜索关键词(必填)
:param search_index: 商品分类,默认"All"(全分类)
:param page: 页码,默认1
:param sort: 排序方式,如"sale rank"
:param response_group: 返回字段组
:return: 搜索结果
"""
# 1. 组装业务参数
params = {
"Keywords": keywords,
"SearchIndex": search_index,
"ItemPage": page,
"ResponseGroup": response_group
}
if sort:
params["Sort"] = sort
# 2. 生成签名URL
signed_url = self.generate_signed_url(params)
try:
# 3. 发送请求
response = requests.get(
url=signed_url,
timeout=20
)
response.raise_for_status()
# 4. 解析响应
result = self.parse_response(response.content)
# 5. 处理响应结果
search_response = result.get("ItemSearchResponse", {})
if "Error" in search_response:
return {
"success": False,
"error_code": search_response["Error"]["Code"],
"error_msg": search_response["Error"]["Message"]
}
items_result = search_response.get("Items", {})
if "Error" in items_result:
return {
"success": False,
"error_code": items_result["Error"]["Code"],
"error_msg": items_result["Error"]["Message"]
}
# 提取分页信息
total_pages = int(items_result.get("TotalPages", 0))
total_results = int(items_result.get("TotalResults", 0))
return {
"success": True,
"total_results": total_results,
"total_pages": total_pages,
"current_page": page,
"items": items_result.get("Item", []) # 商品列表
}
except Exception as e:
return {
"success": False,
"error_msg": f"请求异常: {str(e)}"
}
# 使用示例
if __name__ == "__main__":
# 替换为实际参数
ACCESS_KEY = "your_access_key"
SECRET_KEY = "your_secret_key"
ASSOCIATE_TAG = "your_associate_tag"
REGION = "com" # 美国站点
# 初始化API客户端
api = AmazonSearchApi(ACCESS_KEY, SECRET_KEY, ASSOCIATE_TAG, REGION)
# 搜索"wireless headphones",电子分类,第1页,按销量排序
result = api.item_search(
keywords="wireless headphones",
search_index="Electronics",
page=1,
sort="salesrank", # 按销量排名
response_group="ItemAttributes,Offers,Images,SalesRank"
)
if result["success"]:
print(f"搜索结果: 共 {result['total_results']} 个商品,{result['total_pages']} 页")
print(f"当前第 {result['current_page']} 页,显示 {len(result['items'])} 个商品\n")
# 打印前5个商品信息
for i, item in enumerate(result["items"][:5]):
asin = item.get("ASIN")
title = item.get("ItemAttributes", {}).get("Title", "无标题")
price = item.get("Offers", {}).get("Offer", {}).get(
"OfferListing", {}).get("Price", {}).get("FormattedPrice", "未知价格")
sales_rank = item.get("SalesRank", "无排名")
print(f"商品 {i+1}:")
print(f"ASIN: {asin}")
print(f"标题: {title[:50]}...") # 截断长标题
print(f"价格: {price}")
print(f"销量排名: {sales_rank}")
print(f"主图: {item.get('LargeImage', {}).get('URL', '无图片')}\n")
else:
print(f"搜索失败: {result['error_msg']} (错误码: {result.get('error_code')})")