chinese直男口爆体育生外卖, 99久久er热在这里只有精品99, 又色又爽又黄18禁美女裸身无遮挡, gogogo高清免费观看日本电视,私密按摩师高清版在线,人妻视频毛茸茸,91论坛 兴趣闲谈,欧美 亚洲 精品 8区,国产精品久久久久精品免费

0
  • 聊天消息
  • 系統(tǒng)消息
  • 評(píng)論與回復(fù)
登錄后你可以
  • 下載海量資料
  • 學(xué)習(xí)在線課程
  • 觀看技術(shù)視頻
  • 寫(xiě)文章/發(fā)帖/加入社區(qū)
會(huì)員中心
創(chuàng)作中心

完善資料讓更多小伙伴認(rèn)識(shí)你,還能領(lǐng)取20積分哦,立即完善>

3天內(nèi)不再提示

京東商品詳情商品詳情接口技術(shù)實(shí)現(xiàn):從數(shù)據(jù)抓取到結(jié)構(gòu)化解析全方案

鄧林 ? 來(lái)源:jf_63013664 ? 作者:jf_63013664 ? 2025-09-03 11:07 ? 次閱讀
加入交流群
微信小助手二維碼

掃碼添加小助手

加入工程師交流群

?

商品詳情數(shù)據(jù)是電商分析的核心基礎(chǔ),包含價(jià)格、規(guī)格、庫(kù)存、促銷(xiāo)等關(guān)鍵信息。本文將系統(tǒng)講解京東商品詳情接口的技術(shù)實(shí)現(xiàn),重點(diǎn)解決動(dòng)態(tài)參數(shù)構(gòu)造、多維度數(shù)據(jù)提取、反爬機(jī)制應(yīng)對(duì)等核心問(wèn)題,提供一套合規(guī)高效的技術(shù)方案,同時(shí)嚴(yán)格遵守平臺(tái)規(guī)則與數(shù)據(jù)采集規(guī)范。


一、詳情接口原理與合規(guī)要點(diǎn)

京東商品詳情頁(yè)通過(guò)主接口加載基礎(chǔ)信息,配合多個(gè)輔助接口獲取規(guī)格、庫(kù)存、促銷(xiāo)等細(xì)分?jǐn)?shù)據(jù),采用 JSON 格式返回。實(shí)現(xiàn)該接口需遵循以下合規(guī)要點(diǎn):

請(qǐng)求頻率控制:?jiǎn)?IP 對(duì)同一商品詳情請(qǐng)求間隔不低于 30 秒,單日單 IP 請(qǐng)求不超過(guò) 300 次
數(shù)據(jù)用途限制:僅用于個(gè)人學(xué)習(xí)研究、價(jià)格比較,不得用于商業(yè)競(jìng)爭(zhēng)或惡意爬取
反爬機(jī)制尊重:不使用破解、偽造請(qǐng)求頭等手段,模擬正常用戶瀏覽行為
隱私保護(hù):自動(dòng)過(guò)濾任何可能涉及用戶隱私的信息,僅采集公開(kāi)商品數(shù)據(jù)

商品詳情獲取的核心技術(shù)流程如下:

plaintext

商品ID解析 → 主詳情接口請(qǐng)求 → 輔助接口數(shù)據(jù)補(bǔ)充 → 多源數(shù)據(jù)融合 → 結(jié)構(gòu)化存儲(chǔ)

wKgZPGi3sPmAXtDbAASxyg0BeBU047.pngwKgZPGi3sOCAFwUZAASxyg0BeBU922.png

二、核心技術(shù)實(shí)現(xiàn)


1. 商品詳情參數(shù)生成器

京東商品詳情接口需要特定參數(shù)組合,包括商品 ID、動(dòng)態(tài)簽名等,部分參數(shù)需實(shí)時(shí)生成:

python

運(yùn)行

import time
import random
import hashlib
import string

class JdDetailParamsGenerator:
"""京東商品詳情參數(shù)生成器"""

def __init__(self):
self.app_key = "12574478" # 公共應(yīng)用標(biāo)識(shí)
self.platform = "h5" # 平臺(tái)標(biāo)識(shí)

def generate_main_params(self, sku_id):
"""生成主詳情接口參數(shù)"""
t = str(int(time.time() * 1000))
nonce = self._generate_nonce(16)

params = {
"skuId": sku_id,
"cat": "", # 分類(lèi)ID,留空自動(dòng)獲取
"area": "1_72_2799_0", # 地區(qū)編碼
"shopId": "", # 店鋪ID,留空自動(dòng)獲取
"venderId": "", # 商家ID,留空自動(dòng)獲取
"paramJson": '{"platform":"' + self.platform + '"}',
"t": t,
"nonce": nonce,
"appkey": self.app_key,
"callback": f"jsonp_{int(time.time() * 1000)}_{random.randint(1000, 9999)}"
}

# 生成簽名
params["sign"] = self._generate_sign(params)
return params

def generate_stock_params(self, sku_id, area="1_72_2799_0"):
"""生成庫(kù)存接口參數(shù)"""
return {
"skuId": sku_id,
"area": area,
"cat": "",
"extraParam": '{"originid":"1"}',
"callback": f"jQuery{random.randint(1000000, 9999999)}_{int(time.time() * 1000)}"
}

def generate_price_params(self, sku_id):
"""生成價(jià)格接口參數(shù)"""
return {
"skuIds": f"J_{sku_id}",
"type": "1",
"area": "1_72_2799_0",
"callback": f"jQuery{random.randint(1000000, 9999999)}_{int(time.time() * 1000)}"
}

def _generate_nonce(self, length=16):
"""生成隨機(jī)字符串"""
return ''.join(random.choices(string.ascii_letters + string.digits, k=length))

def _generate_sign(self, params):
"""生成簽名"""
# 按參數(shù)名排序并拼接
sorted_params = sorted(params.items(), key=lambda x: x[0])
sign_str = "&".join([f"{k}={v}" for k, v in sorted_params if k != "sign"])
# 加入固定密鑰(示例)
sign_str += "&secret=jd_detail_demo_key"
# 計(jì)算MD5簽名
return hashlib.md5(sign_str.encode()).hexdigest().upper()

2. 詳情頁(yè)請(qǐng)求管理器

管理多個(gè)接口的請(qǐng)求發(fā)送,處理反爬機(jī)制和會(huì)話維護(hù):

python

運(yùn)行

import time
import random
import requests
from fake_useragent import UserAgent

class JdDetailRequester:
"""京東商品詳情請(qǐng)求管理器"""

def __init__(self, proxy_pool=None):
self.main_api = "https://h5api.m.jd.com/h5/mtop.taobao.detail.getdetail/6.0/"
self.stock_api = "https://c0.3.cn/stock"
self.price_api = "https://p.3.cn/prices/mgets"
self.proxy_pool = proxy_pool or []
self.ua = UserAgent()
self.session = requests.Session()
self.last_request_time = 0
self.min_interval = 30 # 同一商品請(qǐng)求最小間隔(秒)

# 初始化會(huì)話
self._init_session()

def _init_session(self):
"""初始化會(huì)話狀態(tài)"""
# 訪問(wèn)首頁(yè)獲取基礎(chǔ)Cookie
self.session.get(
"https://www.jd.com",
headers=self._get_base_headers(),
timeout=10
)
# 設(shè)置基礎(chǔ)Cookie
self.session.cookies.set("ipLoc-djd", "1-72-2799-0", domain=".jd.com")
self.session.cookies.set("areaId", "1", domain=".jd.com")

def _get_base_headers(self):
"""基礎(chǔ)請(qǐng)求頭"""
return {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "zh-CN,zh;q=0.9",
"Connection": "keep-alive"
}

def _get_headers(self, referer="https://www.jd.com/"):
"""生成詳情頁(yè)請(qǐng)求頭"""
headers = self._get_base_headers()
headers["Referer"] = referer
headers["X-Requested-With"] = "XMLHttpRequest"
return headers

def _get_proxy(self):
"""獲取隨機(jī)代理"""
if not self.proxy_pool:
return None
return random.choice(self.proxy_pool)

def _check_interval(self):
"""控制請(qǐng)求間隔"""
current_time = time.time()
elapsed = current_time - self.last_request_time
if elapsed < self.min_interval:
sleep_time = self.min_interval - elapsed + random.uniform(2, 5)
print(f"請(qǐng)求間隔不足,休眠 {sleep_time:.1f} 秒")
time.sleep(sleep_time)
self.last_request_time = time.time()

def fetch_main_detail(self, params):
"""獲取主詳情數(shù)據(jù)"""
self._check_interval()
headers = self._get_headers()
proxy = self._get_proxy()
proxies = {"http": proxy, "https": proxy} if proxy else None

try:
response = self.session.get(
self.main_api,
params=params,
headers=headers,
proxies=proxies,
timeout=15
)

if response.status_code != 200:
print(f"主詳情請(qǐng)求失敗,狀態(tài)碼: {response.status_code}")
return None

if self._is_blocked(response.text):
print("主詳情請(qǐng)求被攔截")
self._handle_blocked(proxy)
return None

return response.text
except Exception as e:
print(f"主詳情請(qǐng)求異常: {str(e)}")
return None

def fetch_stock(self, params):
"""獲取庫(kù)存數(shù)據(jù)"""
headers = self._get_headers(f"https://item.jd.com/{params['skuId']}.html")
proxy = self._get_proxy()
proxies = {"http": proxy, "https": proxy} if proxy else None

try:
response = self.session.get(
self.stock_api,
params=params,
headers=headers,
proxies=proxies,
timeout=15
)

if response.status_code != 200:
print(f"庫(kù)存請(qǐng)求失敗,狀態(tài)碼: {response.status_code}")
return None

return response.text
except Exception as e:
print(f"庫(kù)存請(qǐng)求異常: {str(e)}")
return None

def fetch_price(self, params):
"""獲取價(jià)格數(shù)據(jù)"""
headers = self._get_headers(f"https://item.jd.com/{params['skuIds'].split('_')[1]}.html")
proxy = self._get_proxy()
proxies = {"http": proxy, "https": proxy} if proxy else None

try:
response = self.session.get(
self.price_api,
params=params,
headers=headers,
proxies=proxies,
timeout=15
)

if response.status_code != 200:
print(f"價(jià)格請(qǐng)求失敗,狀態(tài)碼: {response.status_code}")
return None

return response.text
except Exception as e:
print(f"價(jià)格請(qǐng)求異常: {str(e)}")
return None

def _is_blocked(self, response_text):
"""判斷是否被反爬攔截"""
block_keywords = [
"驗(yàn)證碼",
"訪問(wèn)過(guò)于頻繁",
"安全驗(yàn)證",
"請(qǐng)稍后再試"
]
for keyword in block_keywords:
if keyword in response_text:
return True
return False

def _handle_blocked(self, proxy):
"""處理被攔截情況"""
if proxy and proxy in self.proxy_pool:
self.proxy_pool.remove(proxy)
# 重新初始化會(huì)話
self._init_session()
# 延遲一段時(shí)間
time.sleep(random.uniform(10, 20))

3. 商品詳情數(shù)據(jù)解析器

解析多個(gè)接口返回的數(shù)據(jù),提取結(jié)構(gòu)化商品信息:

python

運(yùn)行

import re
import json
from datetime import datetime
from lxml import etree

class JdDetailParser:
"""京東商品詳情數(shù)據(jù)解析器"""

def __init__(self):
# JSONP格式解析正則
self.jsonp_pattern = re.compile(r'jsonp_d+_d+((.*?))')
self.jquery_pattern = re.compile(r'jQueryd+_d+((.*?));')

def parse_main_detail(self, jsonp_text):
"""解析主詳情數(shù)據(jù)"""
# 提取JSON數(shù)據(jù)
match = self.jsonp_pattern.search(jsonp_text)
if not match:
return None

try:
json_data = json.loads(match.group(1))
except json.JSONDecodeError:
print("主詳情JSON解析失敗")
return None

# 檢查返回狀態(tài)
if json_data.get("ret", [""])[0] != "SUCCESS::調(diào)用成功":
return None

result = {}
data = json_data.get("data", {})

# 基礎(chǔ)信息提取
base = data.get("base", {})
result["product_id"] = base.get("skuId", "")
result["name"] = base.get("name", "").strip()
result["brand"] = base.get("brand", {}).get("name", "")
result["brand_id"] = base.get("brand", {}).get("id", "")
result["shop_name"] = base.get("shopInfo", {}).get("name", "")
result["shop_id"] = base.get("shopInfo", {}).get("shopId", "")
result["is_self"] = base.get("shopInfo", {}).get("isSelf", False)

# 分類(lèi)信息
category = data.get("category", [])
result["categories"] = [c.get("name", "") for c in category if c.get("name")]

# 商品圖片
images = data.get("images", {})
result["main_images"] = [img.get("url", "") for img in images.get("imgList", [])]
result["video_url"] = images.get("videoInfo", {}).get("url", "")

# 商品參數(shù)
item_desc = data.get("itemDesc", {})
result["params"] = self._parse_params(item_desc.get("keyAttributes", []))

# 詳情描述
result["description"] = self._parse_description(item_desc.get("detail", ""))

return result

def parse_stock(self, jquery_text):
"""解析庫(kù)存數(shù)據(jù)"""
# 提取JSON數(shù)據(jù)
match = self.jquery_pattern.search(jquery_text)
if not match:
return None

try:
json_data = json.loads(match.group(1))
except json.JSONDecodeError:
print("庫(kù)存JSON解析失敗")
return None

stock = {
"has_stock": json_data.get("stock", {}).get("hasStock", False),
"stock_num": json_data.get("stock", {}).get("stockNum", 0),
"limit_buy": json_data.get("stock", {}).get("limitBuy", 0),
"warehouse": json_data.get("stock", {}).get("warehouse", "")
}

return stock

def parse_price(self, jquery_text):
"""解析價(jià)格數(shù)據(jù)"""
# 提取JSON數(shù)據(jù)
match = self.jquery_pattern.search(jquery_text)
if not match:
# 嘗試直接解析JSON
try:
json_data = json.loads(jquery_text)
except:
return None
else:
try:
json_data = json.loads(match.group(1))
except json.JSONDecodeError:
print("價(jià)格JSON解析失敗")
return None

if not isinstance(json_data, list) or len(json_data) == 0:
return None

price_info = json_data[0]
return {
"price": float(price_info.get("p", 0)),
"original_price": float(price_info.get("m", 0)) if price_info.get("m") else 0,
"currency": "CNY",
"update_time": datetime.now()
}

def _parse_params(self, key_attributes):
"""解析商品參數(shù)"""
params = {}
for attr in key_attributes:
name = attr.get("name", "").strip()
value = attr.get("value", "").strip()
if name and value:
params[name] = value
return params

def _parse_description(self, detail_html):
"""解析商品詳情描述"""
if not detail_html:
return []

# 提取圖片URL
tree = etree.HTML(detail_html)
img_tags = tree.xpath('//img/@src')

# 處理相對(duì)路徑
images = []
for img in img_tags:
if img.startswith(('http:', 'https:')):
images.append(img)
elif img.startswith('//'):
images.append(f"https:{img}")
elif img.startswith('/'):
images.append(f"https://item.jd.com{img}")

return images

def merge_details(self, main_detail, stock, price):
"""合并多源數(shù)據(jù)"""
if not main_detail:
return None

merged = main_detail.copy()
merged["stock"] = stock if stock else {}
merged["price"] = price if price else {}
merged["crawl_time"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

return merged

4. 商品規(guī)格處理器

解析商品規(guī)格參數(shù)和可選配置:

python

運(yùn)行

import re
import json

class JdSkuSpecificationProcessor:
"""京東商品規(guī)格處理器"""

def __init__(self):
pass

def parse_specifications(self, html_content):
"""從HTML中解析規(guī)格信息"""
try:
# 查找規(guī)格數(shù)據(jù)
pattern = re.compile(r'var specData = (.*?);')
match = pattern.search(html_content)
if not match:
return None

spec_data = json.loads(match.group(1))
return self._process_spec_data(spec_data)
except Exception as e:
print(f"規(guī)格解析失敗: {str(e)}")
return None

def _process_spec_data(self, spec_data):
"""處理規(guī)格數(shù)據(jù)"""
result = {
"spec_groups": [], # 規(guī)格組
"sku_mapping": {} # SKU映射關(guān)系
}

# 處理規(guī)格組
for group in spec_data.get("specList", []):
spec_group = {
"name": group.get("name", ""),
"items": []
}

# 處理規(guī)格項(xiàng)
for item in group.get("specItemList", []):
spec_group["items"].append({
"name": item.get("name", ""),
"img_url": item.get("imgUrl", ""),
"selected": item.get("isSelected", False),
"disabled": item.get("disabled", False)
})

if spec_group["items"]:
result["spec_groups"].append(spec_group)

# 處理SKU映射
for sku in spec_data.get("skuList", []):
sku_id = sku.get("skuId", "")
if not sku_id:
continue

# 規(guī)格路徑
spec_path = []
for path in sku.get("specPath", "").split(";"):
if ":" in path:
_, value = path.split(":", 1)
spec_path.append(value)

result["sku_mapping"][sku_id] = {
"spec_path": spec_path,
"price": sku.get("price", ""),
"stock": sku.get("stock", 0),
"img_url": sku.get("imgUrl", "")
}

return result

def get_sku_by_spec(self, sku_mapping, spec_combination):
"""根據(jù)規(guī)格組合獲取SKU"""
if not sku_mapping or not spec_combination:
return None

# 遍歷SKU映射查找匹配項(xiàng)
for sku_id, sku_info in sku_mapping.items():
if self._match_spec(sku_info["spec_path"], spec_combination):
return {
"sku_id": sku_id,
"price": sku_info["price"],
"stock": sku_info["stock"],
"img_url": sku_info["img_url"]
}

return None

def _match_spec(self, sku_specs, target_specs):
"""匹配規(guī)格組合"""
if len(sku_specs) != len(target_specs):
return False

# 檢查所有規(guī)格是否匹配
for s1, s2 in zip(sku_specs, target_specs):
if s1 != s2:
return False

return True

三、完整商品詳情服務(wù)封裝

整合上述組件,實(shí)現(xiàn)完整的商品詳情獲取服務(wù):

python

運(yùn)行

class JdProductDetailService:
"""京東商品詳情服務(wù)"""

def __init__(self, proxy_pool=None):
self.sku_parser = JdSkuIdParser() # 復(fù)用之前實(shí)現(xiàn)的SKU解析器
self.params_generator = JdDetailParamsGenerator()
self.requester = JdDetailRequester(proxy_pool=proxy_pool)
self.parser = JdDetailParser()
self.spec_processor = JdSkuSpecificationProcessor()

def get_product_detail(self, product_url):
"""
獲取商品完整詳情

:param product_url: 商品詳情頁(yè)URL
:return: 完整的商品詳情字典
"""
# 1. 獲取商品SKU ID
print("解析商品SKU ID...")
sku_id = self.sku_parser.get_sku_id(product_url)
if not sku_id:
print("無(wú)法獲取商品SKU ID")
return None
print(f"商品SKU ID: {sku_id}")

# 2. 獲取主詳情數(shù)據(jù)
print("獲取主詳情數(shù)據(jù)...")
main_params = self.params_generator.generate_main_params(sku_id)
main_response = self.requester.fetch_main_detail(main_params)
if not main_response:
print("主詳情數(shù)據(jù)獲取失敗")
return None
main_detail = self.parser.parse_main_detail(main_response)
if not main_detail:
print("主詳情數(shù)據(jù)解析失敗")
return None

# 3. 獲取庫(kù)存數(shù)據(jù)
print("獲取庫(kù)存數(shù)據(jù)...")
stock_params = self.params_generator.generate_stock_params(sku_id)
stock_response = self.requester.fetch_stock(stock_params)
stock = self.parser.parse_stock(stock_response) if stock_response else None

# 4. 獲取價(jià)格數(shù)據(jù)
print("獲取價(jià)格數(shù)據(jù)...")
price_params = self.params_generator.generate_price_params(sku_id)
price_response = self.requester.fetch_price(price_params)
price = self.parser.parse_price(price_response) if price_response else None

# 5. 獲取規(guī)格數(shù)據(jù)
print("獲取規(guī)格數(shù)據(jù)...")
# 先獲取商品詳情頁(yè)HTML
html_response = self.requester.session.get(
product_url,
headers=self.requester._get_headers(),
timeout=15
)
specifications = self.spec_processor.parse_specifications(html_response.text)

# 6. 合并所有數(shù)據(jù)
full_detail = self.parser.merge_details(main_detail, stock, price)
if full_detail and specifications:
full_detail["specifications"] = specifications

print("商品詳情獲取完成")
return full_detail

四、使用示例與數(shù)據(jù)存儲(chǔ)


1. 基本使用示例

python

運(yùn)行

def main():
# 代理池(實(shí)際使用時(shí)替換為有效代理)
proxy_pool = [
# "http://123.123.123.123:8080",
# "http://111.111.111.111:8888"
]

# 初始化商品詳情服務(wù)
detail_service = JdProductDetailService(proxy_pool=proxy_pool)

# 商品詳情頁(yè)URL
product_url = "https://item.jd.com/100012345678.html" # 替換為實(shí)際商品URL

# 獲取商品詳情
product_detail = detail_service.get_product_detail(product_url)

# 處理結(jié)果
if product_detail:
print(f"n商品名稱(chēng): {product_detail['name']}")
print(f"價(jià)格: {product_detail['price'].get('price', 0)}元")
print(f"是否有貨: {'有貨' if product_detail['stock'].get('has_stock', False) else '無(wú)貨'}")
print(f"店鋪: {product_detail['shop_name']} {'(自營(yíng))' if product_detail['is_self'] else ''}")
print(f"品牌: {product_detail['brand']}")

# 打印部分規(guī)格信息
if "specifications" in product_detail and product_detail["specifications"]["spec_groups"]:
print("n商品規(guī)格:")
for group in product_detail["specifications"]["spec_groups"][:2]: # 只顯示前2個(gè)規(guī)格組
print(f"- {group['name']}: {', '.join([item['name'] for item in group['items'][:5]])}")

# 打印主要參數(shù)
if product_detail["params"]:
print("n主要參數(shù):")
for i, (key, value) in enumerate(list(product_detail["params"].items())[:5]):
print(f"- {key}: {value}")
else:
print("商品詳情獲取失敗")

if __name__ == "__main__":
main()

2. 詳情數(shù)據(jù)存儲(chǔ)工具

python

運(yùn)行

import json
import csv
import pandas as pd
from pathlib import Path
from datetime import datetime

class JdDetailStorage:
"""京東商品詳情存儲(chǔ)工具"""

def __init__(self, storage_dir="./jd_product_details"):
self.storage_dir = Path(storage_dir)
self.storage_dir.mkdir(exist_ok=True, parents=True)

def save_to_json(self, product_detail):
"""保存為JSON格式(完整數(shù)據(jù))"""
sku_id = product_detail.get("product_id", "unknown")
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"jd_detail_{sku_id}_{timestamp}.json"
file_path = self.storage_dir / filename

with open(file_path, "w", encoding="utf-8") as f:
json.dump(product_detail, f, ensure_ascii=False, indent=2, default=str)

print(f"完整詳情已保存至JSON: {file_path}")
return file_path

def save_to_csv(self, product_detail):
"""保存為CSV格式(基礎(chǔ)數(shù)據(jù))"""
sku_id = product_detail.get("product_id", "unknown")
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"jd_detail_basic_{sku_id}_{timestamp}.csv"
file_path = self.storage_dir / filename

# 提取基礎(chǔ)信息
basic_info = {
"product_id": product_detail.get("product_id", ""),
"name": product_detail.get("name", ""),
"brand": product_detail.get("brand", ""),
"price": product_detail.get("price", {}).get("price", 0),
"original_price": product_detail.get("price", {}).get("original_price", 0),
"shop_name": product_detail.get("shop_name", ""),
"shop_id": product_detail.get("shop_id", ""),
"is_self": product_detail.get("is_self", False),
"has_stock": product_detail.get("stock", {}).get("has_stock", False),
"stock_num": product_detail.get("stock", {}).get("stock_num", 0),
"categories": "/".join(product_detail.get("categories", [])),
"crawl_time": product_detail.get("crawl_time", "")
}

# 轉(zhuǎn)換為DataFrame
df = pd.DataFrame([basic_info])
df.to_csv(file_path, index=False, encoding="utf-8-sig")

print(f"基礎(chǔ)信息已保存至CSV: {file_path}")
return file_path

def save_specifications(self, product_detail):
"""單獨(dú)保存規(guī)格數(shù)據(jù)"""
if "specifications" not in product_detail:
print("無(wú)規(guī)格數(shù)據(jù)可保存")
return None

sku_id = product_detail.get("product_id", "unknown")
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"jd_specs_{sku_id}_{timestamp}.json"
file_path = self.storage_dir / filename

with open(file_path, "w", encoding="utf-8") as f:
json.dump(product_detail["specifications"], f, ensure_ascii=False, indent=2)

print(f"規(guī)格數(shù)據(jù)已保存: {file_path}")
return file_path

五、合規(guī)優(yōu)化與風(fēng)險(xiǎn)提示


1. 系統(tǒng)優(yōu)化策略

多級(jí)緩存機(jī)制:實(shí)現(xiàn)內(nèi)存緩存 + 文件緩存的多級(jí)緩存策略

python

運(yùn)行

def get_cached_detail(self, sku_id, max_age=3600):
"""從緩存獲取商品詳情"""
# 先檢查內(nèi)存緩存
# 再檢查文件緩存
# 緩存過(guò)期策略實(shí)現(xiàn)
return None

智能請(qǐng)求調(diào)度:根據(jù)商品重要程度和更新頻率,動(dòng)態(tài)調(diào)整抓取頻率

異常重試機(jī)制:實(shí)現(xiàn)指數(shù)退避重試策略,提高成功率

2. 合規(guī)與風(fēng)險(xiǎn)提示

商業(yè)應(yīng)用前必須獲得京東平臺(tái)書(shū)面授權(quán),遵守《電子商務(wù)法》相關(guān)規(guī)定
不得將采集的商品數(shù)據(jù)用于生成與京東競(jìng)爭(zhēng)的產(chǎn)品或服務(wù)
嚴(yán)格控制請(qǐng)求頻率,避免對(duì)平臺(tái)服務(wù)器造成負(fù)擔(dān)
當(dāng)檢測(cè)到反爬機(jī)制加強(qiáng)時(shí),應(yīng)立即降低請(qǐng)求頻率或暫停服務(wù)
尊重商品信息版權(quán),不濫用采集的數(shù)據(jù)

通過(guò)本文提供的技術(shù)方案,可構(gòu)建一套功能完善的京東商品詳情接口系統(tǒng)。該方案實(shí)現(xiàn)了從多接口數(shù)據(jù)采集、解析到融合的全流程處理,支持商品基礎(chǔ)信息、價(jià)格、庫(kù)存和規(guī)格等多維度數(shù)據(jù)的獲取,為電商數(shù)據(jù)分析、比價(jià)系統(tǒng)等場(chǎng)景提供技術(shù)支持。在實(shí)際應(yīng)用中,需根據(jù)平臺(tái)規(guī)則動(dòng)態(tài)調(diào)整策略,確保系統(tǒng)的穩(wěn)定性和合法性。

?審核編輯 黃宇

聲明:本文內(nèi)容及配圖由入駐作者撰寫(xiě)或者入駐合作網(wǎng)站授權(quán)轉(zhuǎn)載。文章觀點(diǎn)僅代表作者本人,不代表電子發(fā)燒友網(wǎng)立場(chǎng)。文章及其配圖僅供工程師學(xué)習(xí)之用,如有內(nèi)容侵權(quán)或者其他違規(guī)問(wèn)題,請(qǐng)聯(lián)系本站處理。 舉報(bào)投訴
  • API
    API
    +關(guān)注

    關(guān)注

    2

    文章

    1926

    瀏覽量

    65504
  • 京東
    +關(guān)注

    關(guān)注

    2

    文章

    1052

    瀏覽量

    49764
收藏 人收藏
加入交流群
微信小助手二維碼

掃碼添加小助手

加入工程師交流群

    評(píng)論

    相關(guān)推薦
    熱點(diǎn)推薦

    淘寶商品詳情 API:從商品數(shù)據(jù)細(xì)節(jié)中捕捉電商最新流行趨勢(shì),賦能商家決策

    淘寶商品詳情API是洞察電商趨勢(shì)的核心工具,通過(guò)商品信息、主圖視頻、SKU屬性等多維數(shù)據(jù),助力商家精準(zhǔn)捕捉消費(fèi)偏好、優(yōu)化產(chǎn)品設(shè)計(jì)、制定營(yíng)銷(xiāo)與庫(kù)存策略,
    的頭像 發(fā)表于 10-14 10:27 ?93次閱讀
    淘寶<b class='flag-5'>商品</b><b class='flag-5'>詳情</b> API:從<b class='flag-5'>商品數(shù)據(jù)</b>細(xì)節(jié)中捕捉電商最新流行趨勢(shì),賦能商家決策

    API實(shí)戰(zhàn)指南:如何高效采集京東商品詳情數(shù)據(jù)?這幾個(gè)接口必須掌握!

    在電商領(lǐng)域,無(wú)論是做數(shù)據(jù)分析、競(jìng)品監(jiān)控,還是搭建自己的商品推薦系統(tǒng),采集商品詳情數(shù)據(jù)都是一項(xiàng)基礎(chǔ)且重要的工作。
    的頭像 發(fā)表于 10-13 11:39 ?49次閱讀

    京東商品詳情接口實(shí)戰(zhàn)解析調(diào)用優(yōu)化到商業(yè)價(jià)值挖掘(附避坑代碼)

    本文深入解析京東商品詳情接口jd.union.open.goods.detail.query,涵蓋核心特性、權(quán)限限制、關(guān)鍵參數(shù)及調(diào)用避坑指南
    的頭像 發(fā)表于 10-10 09:28 ?189次閱讀
    <b class='flag-5'>京東</b><b class='flag-5'>商品</b><b class='flag-5'>詳情</b><b class='flag-5'>接口</b>實(shí)戰(zhàn)<b class='flag-5'>解析</b>:<b class='flag-5'>從</b>調(diào)用優(yōu)化到商業(yè)價(jià)值挖掘(附避坑代碼)

    別踩分頁(yè)坑!京東商品詳情接口實(shí)戰(zhàn)指南:并發(fā)優(yōu)化到數(shù)據(jù)完整性閉環(huán)

    京東商品詳情接口(jingdong.ware.get)是電商數(shù)據(jù)開(kāi)發(fā)的核心難點(diǎn),本文詳解其權(quán)限申請(qǐng)、分頁(yè)優(yōu)化、多規(guī)格遞歸
    的頭像 發(fā)表于 09-30 15:50 ?730次閱讀

    揭秘淘寶詳情 API 接口:解鎖電商數(shù)據(jù)應(yīng)用新玩法

    在電商的浩瀚宇宙中,淘寶無(wú)疑是一顆璀璨的巨星。對(duì)于開(kāi)發(fā)者、電商從業(yè)者來(lái)說(shuō),獲取淘寶商品的詳細(xì)信息是一項(xiàng)常見(jiàn)且重要的需求。而淘寶詳情 API 接口,就像是一把神奇的鑰匙,能為我們打開(kāi)淘寶商品數(shù)據(jù)
    的頭像 發(fā)表于 09-29 14:30 ?183次閱讀

    當(dāng)當(dāng)網(wǎng)商品詳情接口全方位對(duì)接指南:認(rèn)證機(jī)制到數(shù)據(jù)提取最佳實(shí)踐

    本文詳解當(dāng)當(dāng)網(wǎng)商品詳情接口流程技術(shù)對(duì)接方案,涵蓋OAuth 2.0認(rèn)證、簽名生成、Pytho
    的頭像 發(fā)表于 09-25 09:23 ?253次閱讀

    0 到 1:用 PHP 爬蟲(chóng)優(yōu)雅地拿下京東商品詳情

    在電商數(shù)據(jù)驅(qū)動(dòng)的時(shí)代, 商品詳情數(shù)據(jù) 成為市場(chǎng)分析、價(jià)格監(jiān)控、競(jìng)品調(diào)研的核心燃料。京東作為國(guó)內(nèi)頭部電商平臺(tái),其
    的頭像 發(fā)表于 09-23 16:42 ?370次閱讀
    <b class='flag-5'>從</b> 0 到 1:用 PHP 爬蟲(chóng)優(yōu)雅地拿下<b class='flag-5'>京東</b><b class='flag-5'>商品</b><b class='flag-5'>詳情</b>

    VVIC 平臺(tái)商品詳情接口高效調(diào)用方案簽名驗(yàn)證到數(shù)據(jù)解析流程

    本文詳解VVIC平臺(tái)商品詳情接口調(diào)用流程,涵蓋參數(shù)配置、簽名生成、異常處理與數(shù)據(jù)解析,提供可復(fù)
    的頭像 發(fā)表于 09-23 10:28 ?284次閱讀

    亞馬遜 MWS API 實(shí)戰(zhàn):商品詳情精準(zhǔn)獲取與跨境電商數(shù)據(jù)整合方案

    本文詳細(xì)解析亞馬遜MWS API接口技術(shù)實(shí)現(xiàn),重點(diǎn)解決跨境商品數(shù)據(jù)獲取中的核心問(wèn)題。文章首先介紹MWS
    的頭像 發(fā)表于 09-22 10:05 ?257次閱讀
    亞馬遜 MWS API 實(shí)戰(zhàn):<b class='flag-5'>商品</b><b class='flag-5'>詳情</b>精準(zhǔn)獲取與跨境電商<b class='flag-5'>數(shù)據(jù)</b>整合<b class='flag-5'>方案</b>

    蘇寧開(kāi)放平臺(tái)商品詳情接口實(shí)戰(zhàn):多維度數(shù)據(jù)獲取與結(jié)構(gòu)化處理(附核心代碼 + 避坑指南)

    本文深入解析蘇寧開(kāi)放平臺(tái)商品詳情接口技術(shù)對(duì)接方案,重點(diǎn)介紹其多維度
    的頭像 發(fā)表于 09-18 10:05 ?299次閱讀

    阿里巴巴開(kāi)放平臺(tái)商品詳情接口實(shí)操:數(shù)據(jù)解析 + 核心實(shí)現(xiàn)方案(附避坑指南)

    本文提供阿里巴巴商品詳情接口的實(shí)用開(kāi)發(fā)指南,涵蓋B2B場(chǎng)景下的核心功能實(shí)現(xiàn)。重點(diǎn)解析接口基礎(chǔ)參數(shù)
    的頭像 發(fā)表于 09-17 13:54 ?148次閱讀

    淘寶/天貓:通過(guò)商品詳情API實(shí)現(xiàn)多店鋪商品信息批量同步,確保價(jià)格、庫(kù)存實(shí)時(shí)更新

    ? 在電商運(yùn)營(yíng)中,管理多個(gè)淘寶或天貓店鋪的商品信息(如價(jià)格和庫(kù)存)是一項(xiàng)繁瑣的任務(wù)。手動(dòng)更新耗時(shí)耗力,且容易出錯(cuò),導(dǎo)致價(jià)格不一致或庫(kù)存超賣(mài)。通過(guò)淘寶/天貓開(kāi)放平臺(tái)提供的商品詳情API,我們可以
    的頭像 發(fā)表于 09-08 16:05 ?329次閱讀
    淘寶/天貓:通過(guò)<b class='flag-5'>商品</b><b class='flag-5'>詳情</b>API<b class='flag-5'>實(shí)現(xiàn)</b>多店鋪<b class='flag-5'>商品</b>信息批量同步,確保價(jià)格、庫(kù)存實(shí)時(shí)更新

    eBay 商品詳情 API 深度解析基礎(chǔ)信息到變體數(shù)據(jù)獲取方案

    通過(guò)本文提供的方案,開(kāi)發(fā)者可以快速實(shí)現(xiàn) eBay 商品詳情數(shù)據(jù)的獲取和處理,為跨境電商應(yīng)用提供豐富的商品
    的頭像 發(fā)表于 08-18 10:17 ?429次閱讀
    eBay <b class='flag-5'>商品</b><b class='flag-5'>詳情</b> API 深度<b class='flag-5'>解析</b>:<b class='flag-5'>從</b>基礎(chǔ)信息到變體<b class='flag-5'>數(shù)據(jù)</b>獲取<b class='flag-5'>全</b><b class='flag-5'>方案</b>

    如何利用京東商品詳情id拿到商品的詳細(xì)信息 示例展示

    利用京東商品詳情 ID(即 SKU ID)獲取商品詳細(xì)信息,可通過(guò)京東開(kāi)放平臺(tái)官方 API 或非官方接口
    的頭像 發(fā)表于 07-10 09:37 ?631次閱讀

    《仿盒馬》app開(kāi)發(fā)技術(shù)分享-- 商品詳情頁(yè)(10)

    技術(shù)棧 Appgallery connect 開(kāi)發(fā)準(zhǔn)備 上一節(jié)我們實(shí)現(xiàn)了自定義標(biāo)題欄和商品詳情數(shù)據(jù)接收,我們已經(jīng)拿到了想要的
    發(fā)表于 06-30 08:47