在B2B电商领域,1688作为国内最大的供应链平台,其商品数据对企业采购决策、市场分析至关重要。传统爬虫方案面临三大致命问题:
官方API核心优势:
aliexpress.product.detail.get(商品详情)app_key = "您的AppKey" app_secret = "您的AppSecret" access_token = "通过OAuth2.0获取"
1688采用 双重签名验证:
app_secret对参数加密access_token验证Python签名示例:
import hashlib
import urllib.parse
def generate_sign(params, app_secret):
# 参数排序+URL编码
sorted_params = sorted(params.items())
query_str = '&'.join([f'{k}={urllib.parse.quote_plus(str(v))}' for k, v in sorted_params])
# HMAC-SHA1加密
sign = hmac.new(app_secret.encode(), query_str.encode(), hashlib.sha1).hexdigest()
return sign.upper()import requests
import json
import time
app_key = "YOUR_APP_KEY"
app_secret = "YOUR_APP_SECRET"
product_id = "商品ID" # 示例:从商品URL中获取如https://detail.1688.com/offer/123456.html
# 构造基础参数
params = {
"app_key": app_key,
"method": "aliexpress.product.detail.get",
"product_id": product_id,
"timestamp": str(int(time.time() * 1000)), # 1688要求13位时间戳
"format": "json",
"v": "2.0"
}
# 生成签名
params["sign"] = generate_sign(params, app_secret)
# 添加access_token(部分接口需要)
headers = {
"Authorization": f"Bearer {access_token}"
}
try:
response = requests.get(
"https://gw.open.1688.com/openapi/param2/2/portals.open/api/",
params=params,
headers=headers
)
data = response.json()
# 提取关键字段
product_info = data["result"]["productInfo"]
sku_list = product_info["skuList"]
print(f"商品标题:{product_info['subject']}")
print(f"批发价格区间:{product_info['priceRange']}")
print(f"最小起订量:{product_info['moq']}")
print("SKU详情:")
for sku in sku_list:
print(f"规格:{sku['spec']} | 库存:{sku['stock']} | 价格:{sku['price']}")
except Exception as e:
print(f"API调用失败:{str(e)}")
print(f"完整响应:{response.text}")返回数据结构示例:
{
"result": {
"productInfo": {
"productId": "123456",
"subject": "2024新款不锈钢保温杯",
"priceRange": "15.80-18.60",
"moq": 100,
"skuList": [
{
"skuId": "7890",
"spec": "500ml 银色",
"price": "15.80",
"stock": 2000
},
{
"skuId": "7891",
"spec": "500ml 黑色",
"price": "16.20",
"stock": 1500
}
]
}
}
}import matplotlib.pyplot as plt
prices = [float(sku['price']) for sku in sku_list]
plt.boxplot(prices)
plt.title("SKU价格分布")
plt.savefig('price_distribution.png')getToken方法requests_oauthlib库简化授权流程from requests_oauthlib import OAuth2Session client = OAuth2Session( client_id=app_key, redirect_uri="您的回调地址" ) authorization_url, _ = client.authorization_url( "https://auth.1688.com/oauth/authorize" ) # 引导用户访问authorization_url完成授权
from cryptography.fernet import Fernet key = Fernet.generate_key() cipher_suite = Fernet(key) encrypted_data = cipher_suite.encrypt( json.dumps(product_info).encode() )
import logging
logging.basicConfig(filename='api_audit.log', level=logging.INFO)
logging.info(f"[{datetime.now()}] 查询商品ID:{product_id}")pip install alibaba-python-sdk立即行动:访问1688开放平台完成企业认证,解锁B2B数据宝藏!遇到技术难题?欢迎在评论区交流,获取作者实时解答。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70026910/viewspace-3073678/ ,如需转载,请注明出处,否则将追究法律责任。