利用 Python 爬虫获取京东商品详情 API 返回值说明及代码示例

117 阅读4分钟

在电商领域,京东作为国内知名的电商平台,提供了丰富的商品信息。通过调用京东商品详情 API,我们可以获取商品的详细信息,如商品标题、价格、图片、描述等。这些信息对于数据分析、价格监控、商品推荐等场景具有重要价值。本文将详细介绍如何使用 Python 爬虫技术调用京东商品详情 API,并对返回值进行详细说明。

一、准备工作

1. 注册京东开放平台账号

要使用京东商品详情 API,首先需要在京东开放平台(open.jd.com/)注册账号,并创建应用以获取 App KeyApp Secret。这些是调用 API 所必需的凭证。

2. 安装必要的 Python 库

确保你的 Python 环境中已经安装了以下库:

  • requests:用于发送 HTTP 请求。
  • json:用于处理 JSON 数据。

如果尚未安装这些库,可以通过以下命令进行安装:

pip install requests

二、代码实现

以下是一个完整的 Python 示例代码,展示如何调用京东商品详情 API,并处理返回的数据。

1. 发送 HTTP 请求

使用 requests 库发送请求,并获取 API 返回的数据。

import requests
import json
import hashlib
import time

def generate_signature(app_key, app_secret, timestamp):
    # 生成签名
    sign_str = app_key + timestamp + app_secret
    return hashlib.md5(sign_str.encode('utf-8')).hexdigest()

def get_jd_product_detail(app_key, app_secret, sku_id):
    timestamp = str(int(time.time()))
    signature = generate_signature(app_key, app_secret, timestamp)

    api_url = "https://api.jd.com/routerjson"
    params = {
        'method': 'item_detail',
        'app_key': app_key,
        'timestamp': timestamp,
        'v': '2.0',
        'sign_method': 'md5',
        'sign': signature,
        'param_json': json.dumps({'skuIds': sku_id})
    }

    response = requests.get(api_url, params=params)
    if response.status_code == 200:
        return response.json()
    else:
        print(f"请求失败,状态码:{response.status_code}")
        return None

def parse_response(data):
    if data['code'] == '0':
        items = data['jingdong_item_detail_response']['items']
        for item in items:
            num_iid = item['num_iid']
            title = item['title']
            detail_url = item['detail_url']
            pic_url = item['pic_url']
            price = item['price']
            description = item['description']

            print(f"商品 ID: {num_iid}")
            print(f"商品标题: {title}")
            print(f"商品详情页 URL: {detail_url}")
            print(f"商品图片 URL: {pic_url}")
            print(f"商品价格: {price}")
            print(f"商品描述: {description}")
    else:
        print(f"API 请求失败,错误信息: {data['errorMessage']}")

if __name__ == '__main__':
    app_key = 'your_app_key'  # 替换为你的 App Key
    app_secret = 'your_app_secret'  # 替换为你的 App Secret
    sku_id = '123456'  # 替换为商品的 SKU ID

    response_data = get_jd_product_detail(app_key, app_secret, sku_id)
    if response_data:
        parse_response(response_data)

2. 解析返回的 JSON 数据

解析 API 返回的 JSON 数据,并提取商品的详细信息。

def parse_response(data):
    if data['code'] == '0':
        items = data['jingdong_item_detail_response']['items']
        for item in items:
            num_iid = item['num_iid']
            title = item['title']
            detail_url = item['detail_url']
            pic_url = item['pic_url']
            price = item['price']
            description = item['description']

            print(f"商品 ID: {num_iid}")
            print(f"商品标题: {title}")
            print(f"商品详情页 URL: {detail_url}")
            print(f"商品图片 URL: {pic_url}")
            print(f"商品价格: {price}")
            print(f"商品描述: {description}")
    else:
        print(f"API 请求失败,错误信息: {data['errorMessage']}")

三、API 返回值说明

京东商品详情 API 的返回值是一个 JSON 对象,其结构如下:

返回值示例

{
    "code": "0",
    "errorMessage": "success",
    "jingdong_item_detail_response": {
        "items": [
            {
                "num_iid": "1234567890",
                "title": "商品标题",
                "detail_url": "https://item.jd.com/1234567890.html",
                "pic_url": "https://img10.360buyimg.com/n1/s200x200_jfs/t1/123456/1/1234567890.jpg",
                "price": "120.00",
                "description": "商品详细描述"
            }
        ]
    }
}

返回值字段说明

  • code:返回的状态码,表示请求的结果。0 表示成功,其他值表示失败。

  • errorMessage:错误信息,描述了返回状态码对应的错误原因。

  • jingdong_item_detail_response:商品详情信息的响应数据。

    • items:商品列表,包含多个商品的详细信息。

      • num_iid:商品的唯一标识 ID。
      • title:商品标题。
      • detail_url:商品详情页的 URL。
      • pic_url:商品图片的 URL。
      • price:商品当前价格。
      • description:商品详细描述。

四、注意事项

1. API 使用限制

京东 API 可能对请求频率和数据量有限制。建议在实际使用中合理安排请求间隔,避免被封禁。

2. 数据隐私

确保遵守京东开放平台的使用条款,不要滥用数据。

3. 异常处理

在请求过程中可能会遇到网络问题、API 限制或其他错误。建议使用 try-except 语句捕获异常,并合理处理。

4. 签名生成

根据京东 API 文档,生成签名是调用 API 的必要步骤。确保正确实现签名生成逻辑。

五、总结

通过上述步骤和代码,你可以使用 Python 爬虫技