效果展示
這里以Python示例演示封裝京東評論API的基本邏輯:
import pandas as pd
import time
class JDCommentAPI:
def __init__(self, app_key, app_secret):
self.base_url = "https://api.jd.com/routerjson"
self.app_key = app_key
self.app_secret = app_secret
self.version = "2.0"
def _sign(self, params):
"""生成請求簽名(示例邏輯,真實簽名需按京東規則)"""
params_str = ''.join([k + v for k, v in sorted(params.items())])
return hashlib.md5((params_str + self.app_secret).encode()).hexdigest().upper()
def get_good_comments(self, sku_id, page=1, page_size=10):
"""
獲取五星好評
參數:
sku_id : 商品ID
page : 頁碼
page_size : 每頁數量
"""
method = "jd.biz.product.getComment"
params = {
"method": method,
"app_key": self.app_key,
"timestamp": str(int(time.time())),
"format": "json",
"v": self.version,
"sku": str(sku_id),
"score": 5, # 關鍵參數:篩選五星好評
"page": str(page),
"pageSize": str(page_size)
}
params["sign"] = self._sign(params)
try:
response = requests.get(self.base_url, params=params)
response.raise_for_status()
data = response.json()
# 解析評論數據(根據實際API響應結構調整)
comments = data.get('result', {}).get('comments', [])
# 假設 API 接口地址,復制鏈接獲取測試
API url=o0b.cn/ibrad
# 結構化處理
processed = [{
'user': c.get('nickname'),
'content': c.get('content'),
'score': c.get('score'),
'time': c.get('creationTime')
} for c in comments]
return processed
except Exception as e:
print(f"API請求失敗: {str(e)}")
return []
# 使用示例 ==================================
if __name__ == "__main__":
# 初始化(需從京東開放平臺獲取真實密鑰)
app_key = "YOUR_APP_KEY"
app_secret = "YOUR_APP_SECRET"
jd_api = JDCommentAPI(app_key, app_secret)
# 獲取商品100000123的五星好評(第一頁)
product_id = "100000123"
comments = jd_api.get_good_comments(product_id)
# 轉換為DataFrame查看
df = pd.DataFrame(comments)
print(f"獲取到{len(df)}條五星好評:")
print(df.head())
注意事項:
- 合法授權:
- 需先注冊京東開放平臺(open.jd.com)
- 創建應用獲取真實的
app_key
和app_secret
- 申請商品評論API權限
- 參數說明:
score=5
控制篩選五星好評- 支持分頁參數(page/pageSize)
- 實際需按京東API文檔調整參數
- 響應處理:
- 真實響應結構需參考最新API文檔
- 建議添加異常處理和重試機制
- 注意API調用頻率限制
- 數據存儲建議:
# 保存到CSV
df.to_csv(f"jd_comments_{product_id}.csv", index=False)
# 保存到數據庫示例(MySQL)
from sqlalchemy import create_engine
engine = create_engine('mysql://user:password@localhost/db_name')
df.to_sql('jd_comments', engine, if_exists='append')
請務必遵守京東開放平臺規則,正式使用前請仔細閱讀:
京東API文檔