在跨境電商開發領域,eBay 作為全球最大的在線交易平臺之一,其開放 API 為開發者提供了豐富的商品數據獲取能力。本文將聚焦 eBay 關鍵字搜索商品列表接口的實現,涵蓋 OAuth2.0 認證、高級搜索參數配置、分頁策略及完整代碼實現,幫助開發者快速構建穩定的 eBay 商品檢索功能。
一、eBay 搜索 API 基礎信息
eBay 提供的 Finding API 是獲取商品列表的核心接口,支持通過關鍵字、分類、價格區間等多維度篩選商品。
核心特點:
- 基于 RESTful 架構設計,支持 JSON/XML 響應格式
- 采用 OAuth2.0 認證機制,安全性更高
- 提供豐富的篩選參數,支持精確搜索
- 單頁最大返回 100 條數據,支持分頁查詢
接口端點:https://api.ebay.com/services/search/FindingService/v1
二、認證機制詳解
eBay Finding API 使用 OAuth2.0 進行身份驗證,獲取訪問令牌的步驟如下:
- 在 eBay 開發者平臺創建應用,獲取 Client ID 和 Client Secret
- 通過客戶端憑證流程 (Client Credentials Flow) 獲取訪問令牌
- 令牌有效期為 7200 秒 (2 小時),過期前需重新獲取
點擊獲取key和secret
三、核心搜索參數說明
-
基礎參數:
keywords
:搜索關鍵字(必填)categoryId
:商品分類 ID(可選)itemFilter
:過濾條件(價格區間、賣家類型等)sortOrder
:排序方式(BestMatch、PricePlusShippingLowest 等)
-
分頁參數:
paginationInput.pageNumber
:頁碼paginationInput.entriesPerPage
:每頁條數 (1-100)
-
輸出控制:
outputSelector
:指定返回字段,減少數據傳輸量
四、完整代碼實現
下面是使用 Python 實現的 eBay 關鍵字搜索商品列表功能,包含令牌管理和搜索邏輯:
eBay關鍵字搜索商品列表接口實現
import requests
import time
import json
from typing import Dict, List, Optionalclass EbaySearchAPI:def __init__(self, client_id: str, client_secret: str, site_id: str = '0'):"""初始化eBay搜索API客戶端:param client_id: 應用的Client ID:param client_secret: 應用的Client Secret:param site_id: 站點ID,0表示美國站"""self.client_id = client_idself.client_secret = client_secretself.site_id = site_idself.base_url = "https://api.ebay.com/services/search/FindingService/v1"self.oauth_url = "https://api.ebay.com/identity/v1/oauth2/token"self.access_token = Noneself.token_expiry = 0 # 令牌過期時間戳def _get_access_token(self) -> Optional[str]:"""獲取或刷新訪問令牌"""# 檢查令牌是否有效if self.access_token and time.time() < self.token_expiry:return self.access_token# 準備請求參數headers = {"Content-Type": "application/x-www-form-urlencoded","Authorization": f"Basic {self._encode_credentials()}"}data = {"grant_type": "client_credentials","scope": "https://api.ebay.com/oauth/api_scope"}try:response = requests.post(self.oauth_url,headers=headers,data=data,timeout=10)response.raise_for_status()token_data = response.json()# 保存令牌及過期時間self.access_token = token_data["access_token"]self.token_expiry = time.time() + token_data["expires_in"] - 60 # 提前60秒刷新return self.access_tokenexcept requests.exceptions.RequestException as e:print(f"獲取令牌失敗: {str(e)}")return Nonedef _encode_credentials(self) -> str:"""編碼客戶端憑證"""import base64credentials = f"{self.client_id}:{self.client_secret}".encode("utf-8")return base64.b64encode(credentials).decode("utf-8")def search_products(self,keywords: str,page: int = 1,per_page: int = 20,min_price: Optional[float] = None,max_price: Optional[float] = None,sort_order: str = "BestMatch") -> Dict:"""搜索eBay商品:param keywords: 搜索關鍵字:param page: 頁碼:param per_page: 每頁條數(1-100):param min_price: 最低價格:param max_price: 最高價格:param sort_order: 排序方式:return: 搜索結果"""# 獲取訪問令牌token = self._get_access_token()if not token:return {"error": "無法獲取訪問令牌"}# 準備請求參數params = {"OPERATION-NAME": "findItemsAdvanced","SERVICE-VERSION": "1.13.0","SECURITY-APPNAME": self.client_id,"GLOBAL-ID": f"EBAY-{self.site_id}","keywords": keywords,"paginationInput.pageNumber": page,"paginationInput.entriesPerPage": per_page,"sortOrder": sort_order,"response-data-format": "JSON"}# 添加價格過濾條件filter_index = 0if min_price is not None:params[f"itemFilter({filter_index}).name"] = "MinPrice"params[f"itemFilter({filter_index}).value"] = min_priceparams[f"itemFilter({filter_index}).paramName"] = "Currency"params[f"itemFilter({filter_index}).paramValue"] = "USD"filter_index += 1if max_price is not None:params[f"itemFilter({filter_index}).name"] = "MaxPrice"params[f"itemFilter({filter_index}).value"] = max_priceparams[f"itemFilter({filter_index}).paramName"] = "Currency"params[f"itemFilter({filter_index}).paramValue"] = "USD"filter_index += 1# 設置請求頭headers = {"Authorization": f"Bearer {token}","X-EBAY-SOA-REQUEST-DATA-FORMAT": "JSON"}try:response = requests.get(self.base_url,params=params,headers=headers,timeout=15)response.raise_for_status()return self._parse_response(response.json())except requests.exceptions.RequestException as e:print(f"搜索請求失敗: {str(e)}")return {"error": str(e)}def _parse_response(self, response: Dict) -> Dict:"""解析API響應,提取有用信息"""result = {"total_items": 0,"page": 0,"per_page": 0,"items": []}try:search_result = response["findItemsAdvancedResponse"][0]# 提取分頁信息pagination = search_result["paginationOutput"][0]result["total_items"] = int(pagination["totalEntries"][0])result["page"] = int(pagination["pageNumber"][0])result["per_page"] = int(pagination["entriesPerPage"][0])# 提取商品信息if "searchResult" in search_result and len(search_result["searchResult"][0]["item"]) > 0:for item in search_result["searchResult"][0]["item"]:result["items"].append({"item_id": item["itemId"][0],"title": item["title"][0],"price": {"value": float(item["sellingStatus"][0]["currentPrice"][0]["__value__"]),"currency": item["sellingStatus"][0]["currentPrice"][0]["@currencyId"]},"url": item["viewItemURL"][0],"location": item.get("location", [""])[0],"shipping_cost": float(item["shippingInfo"][0]["shippingServiceCost"][0]["__value__"]),"is_top_rated": "topRatedListing" in item and item["topRatedListing"][0].lower() == "true"})except (KeyError, IndexError, ValueError) as e:print(f"解析響應失敗: {str(e)}")result["error"] = f"解析響應失敗: {str(e)}"return result# 使用示例
if __name__ == "__main__":# 替換為你的eBay應用憑證CLIENT_ID = "your_client_id"CLIENT_SECRET = "your_client_secret"# 初始化API客戶端(美國站)ebay_api = EbaySearchAPI(CLIENT_ID, CLIENT_SECRET, site_id='0')# 搜索商品search_result = ebay_api.search_products(keywords="wireless headphones",page=1,per_page=20,min_price=20.0,max_price=100.0,sort_order="PricePlusShippingLowest")# 處理搜索結果if "error" not in search_result:print(f"找到 {search_result['total_items']} 個商品")print(f"當前第 {search_result['page']} 頁,共 {search_result['per_page']} 條/頁\n")for idx, item in enumerate(search_result["items"], 1):print(f"{idx}. {item['title']}")print(f" 價格: {item['price']['currency']} {item['price']['value']}")print(f" 運費: {item['price']['currency']} {item['shipping_cost']}")print(f" 鏈接: {item['url']}\n")else:print(f"搜索失敗: {search_result['error']}")
?
五、代碼核心功能解析
-
令牌管理機制:
- 自動處理令牌的獲取與刷新,無需手動干預
- 提前 60 秒刷新令牌,避免請求時令牌過期
- 使用 Base64 編碼客戶端憑證,符合 OAuth2.0 規范
-
搜索參數處理:
- 支持多維度篩選,包括價格區間、排序方式等
- 靈活處理可選參數,僅在提供時添加到請求中
- 嚴格遵循 eBay API 的參數命名規范
-
響應解析優化:
- 將原始 API 響應轉換為更友好的字典格式
- 提取核心商品信息,去除冗余數據
- 包含錯誤處理,提高代碼健壯性
-
多站點支持:
- 通過 site_id 參數支持不同國家 / 地區的 eBay 站點
- 默認為美國站 (0),可根據需求切換為其他站點
六、實戰注意事項
-
API 調用限制:
- Finding API 有調用頻率限制,默認每日 10,000 次
- 建議實現請求間隔控制,避免觸發限流
-
站點選擇:
- 不同站點的商品和價格存在差異
- 完整站點 ID 列表可參考 eBay 開發者文檔
-
錯誤處理:
- 常見錯誤包括令牌過期、參數錯誤、頻率超限
- 實際開發中應根據錯誤代碼實現針對性處理
-
數據緩存:
- 對熱門搜索詞結果進行緩存,減少 API 調用
- 緩存時間建議設置為 15-30 分鐘,保證數據新鮮度
七、功能擴展建議
- 實現批量搜索功能,支持多關鍵字同時查詢
- 添加商品圖片 URL 提取,豐富展示內容
- 集成價格趨勢分析,提供歷史價格數據
- 實現搜索結果的本地存儲,支持離線查看
通過本文介紹的方法,開發者可以快速集成 eBay 的商品搜索功能,為跨境電商應用提供穩定可靠的數據源。在實際開發中,需遵守 eBay 開發者協議,合理使用 API 獲取的數據。