import requests
import json
def get_taobao_product_data(app_key, app_secret, keywords):
# 构造请求参数
params = {
'app_key': app_key,
'method': 'taobao.items.search',
'timestamp': str(int(time.time())),
'format': 'json',
'v': '2.0',
'sign_method': 'md5',
'fields': 'num_iid,title,pict_url,price,nick,seller_id',
'keyword': keywords,
'page_no': '1',
'page_size': '10'
}
# 根据App Secret生成签名
params['sign'] = generate_sign(params, app_secret)
# 发送请求
response = requests.get('http://gw.api.taobao.com/router/rest', params=params)
# 解析响应数据
data = json.loads(response.text)
if data['success']:
return data['result']['items']
else:
return None
def generate_sign(params, app_secret):
# 将参数按照字母顺序排序
sorted_params = sorted(params.items(), key=lambda x: x[0])
# 构造待签名字符串
sign_string = app_secret + params['timestamp'] + params['method']
for key, value in sorted_params:
if key != 'sign' and value is not None:
sign_string += key + value
# 生成签名
import hashlib
md5 = hashlib.md5()
md5.update(sign_string.encode('utf-8'))
return md5.hexdigest().upper()
# 使用你的App Key和App Secret替换以下占位符
app_key = 'YOUR_APP_KEY'
app_secret = 'YOUR_APP_SECRET'
keywords = '商品关键词' # 你要搜索的商品关键词
# 调用函数获取商品数据
product_data = get_taobao_product_data(app_key, app_secret, keywords)
if product_data is not None:
for item in product_data:
print('商品ID:', item['num_iid'])
print('商品标题:', item['title'])
print('商品图片URL:', item['pict_url'])
print('商品价格:', item['price'])
print('卖家昵称:', item['nick'])
print('卖家ID:', item['seller_id'])
print('--------------')
else:
print('获取商品数据失败')
评论