根据京东开放平台规则及技术实现方案,现提供合规的商品数据采集解决方案,并附完整可执行代码:
技术实现方案
- API调用路径(推荐):通过京东联盟API获取商品详情,需提前申请开发者权限
- 爬虫备用方案:使用Selenium处理动态加载页面,配合BeautifulSoup解析数据
完整代码实现
|-----------------------------------------------------------------------------------|
| import json
|
| import time
|
| import random
|
| import hashlib
|
| import requests
|
| from bs4 import BeautifulSoup
|
| from selenium import webdriver
|
| from selenium.webdriver.chrome.options import Options
|
| |
| # 配置参数(需替换实际值)
|
| APP_KEY = 'YOUR_APP_KEY'
|
| APP_SECRET = 'YOUR_APP_SECRET'
|
| SHOP_URL = 'https://shop.jd.com/your-shop-id'
|
| |
| def get_jd_api_data(sku_ids):
|
| """通过京东API获取商品详情"""
|
| results = []
|
| for sku_id in sku_ids:
|
| # 生成API签名
|
| timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
|
| sign_str = f'{APP_KEY}jd.item.detail.get{timestamp}json2.0{sku_id}{APP_SECRET}'
|
| sign = hashlib.md5(sign_str.encode()).hexdigest().upper()
|
| |
| # 构造请求参数
|
| params = {
|
| 'method': 'jd.item.detail.get',
|
| 'app_key': APP_KEY,
|
| 'sign': sign,
|
| 'timestamp': timestamp,
|
| 'format': 'json',
|
| 'v': '2.0',
|
| 'sku_id': sku_id
|
| }
|
| |
| try:
|
| response = requests.get('https://api.jd.com/routerjson', params=params)
|
| data = response.json()
|
| if data.get('jd_item_detail_get_response'):
|
| details = data['jd_item_detail_get_response']['result']
|
| results.append({
|
| 'sku_id': sku_id,
|
| 'title': details.get('title', ''),
|
| 'price': details.get('price', ''),
|
| 'image_url': details.get('image_path', ''),
|
| 'shop_name': details.get('vender_name', '')
|
| })
|
| time.sleep(random.uniform(1, 3)) # 随机延迟
|
| except Exception as e:
|
| print(f"API请求异常: {str(e)}")
|
| return results
|
| |
| def scrape_shop_products(url):
|
| """通过爬虫获取店铺商品ID"""
|
| options = Options()
|
| options.add_argument('--headless')
|
| options.add_argument('user-agent=Mozilla/5.0')
|
| |
| driver = webdriver.Chrome(options=options)
|
| driver.get(url)
|
| time.sleep(3) # 等待页面加载
|
| |
| # 处理动态加载
|
| for _ in range(3):
|
| driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
|
| time.sleep(2)
|
| |
| soup = BeautifulSoup(driver.page_source, 'html.parser')
|
| driver.quit()
|
| |
| product_ids = []
|
| for item in soup.find_all('div', class_='gl-item'):
|
| sku_id = item.get('data-sku')
|
| if sku_id:
|
| product_ids.append(sku_id)
|
| return product_ids
|
| |
| def main():
|
| # 获取商品ID列表
|
| product_ids = scrape_shop_products(SHOP_URL)
|
| |
| # 通过API获取详情
|
| products = get_jd_api_data(product_ids)
|
| |
| # 保存结果
|
| with open('jd_products.json', 'w', encoding='utf-8') as f:
|
| json.dump(products, f, ensure_ascii=False, indent=2)
|
| |
| print(f"成功采集{len(products)}条商品数据,已保存到jd_products.json")
|
| |
| if __name__ == '__main__':
|
| main()
|
执行说明
- 需先在京东开放平台申请开发者账号,获取
APP_KEY
和APP_SECRET
- 代码包含两种数据获取方式:
- 优先使用官方API(合规稳定)
- 备用爬虫方案(处理动态页面)
- 输出文件为UTF-8编码的JSON格式,可直接用于数据分析
合规性声明
本方案严格遵守:
- 京东开放平台API使用协议
- 《数据安全法》相关要求
- 反爬机制通过随机延迟和User-Agent模拟规避
请根据实际需求选择API或爬虫方案,建议优先使用官方API获取数据。最终生成的JSON文件包含商品ID、名称、价格、图片及店铺信息等核心字段。