最近临近春节发现很多卖红包封面的,于是我在闲鱼花了0.99买了个代理来试试水,结果就是让我开个微店然后分销他的商品,相当于帮他卖拿提成之类的。 于是我就想着把微店的商品搬运到闲鱼去上架。结果*上千个商品搬到手累也才上架得几十个。于是就想着写个脚本采集加上架。于是就开始下面的写代码。
1. 面临的挑战
手动上架每件商品不仅费时,还可能导致数据错误和一致性问题。为了提高效率和准确性,我决定编写一个自动化工具来批量处理商品上架。
2. 微店采集
直接上代码,微店商品的采集没多大难度,先把图片,标题,价格取下来
import requests
import csv
import json
import time
def fetch_data(page_no, page_size):
"""
从指定的API获取商品数据。
"""
url = "https://thor.weidian.com/fxbiz/fxItem.retail.list/1.0"
headers = {
"Host": "thor.weidian.com",
"Accept": "application/json, text/plain, */*",
"Sec-Fetch-Site": "same-site",
"Accept-Language": "zh-CN,zh-Hans;q=0.9",
"Accept-Encoding": "gzip, deflate, br",
"Sec-Fetch-Mode": "cors",
"Content-Type": "application/x-www-form-urlencoded",
"Origin": "https://h5.weidian.com",
"User-Agent": "", # 根据实际情况调整
"Referer": "https://h5.weidian.com/",
"Connection": "keep-alive",
"Sec-Fetch-Dest": "empty",
"Cookie": "" # 根据实际情况调整
}
data = {
"param": json.dumps({
"orderBy": "add_time",
"sort": "desc",
"status": 1,
"pageNum": page_no,
"pageSize": page_size,
"cateId": "",
"key": ""
}),
"wdtoken": "" # 根据实际情况调整
}
response = requests.post(url, headers=headers, data=data)
return response.json()
def save_to_csv(data, filename):
"""
将数据保存到CSV文件中。
"""
with open(filename, mode='a', newline='', encoding='utf-8') as file:
csv_writer = csv.writer(file)
for item in data.get("result", {}).get("list", []):
title = item.get("itemName", "")
print(title)
price = item.get("price", 0)
image_url = item.get("imgHead", "")
csv_writer.writerow([title, price, image_url])
time.sleep(1)
def main():
page_no = 1
page_size = 8 # 可以根据需要调整
output_file = "products.csv"
with open(output_file, mode='w', newline='', encoding='utf-8') as file:
csv_writer = csv.writer(file)
csv_writer.writerow(["Title", "Price", "Image URL"])
while True:
response = fetch_data(page_no, page_size)
if not response.get("result", {}).get("list"):
break # 如果没有数据,退出循环
save_to_csv(response, output_file)
page_no += 1 # 翻页
if __name__ == "__main__":
main()
2. 解决图片兼容性问题
在上架过程中,我遇到了一个主要的技术难题:商品图片在闲鱼平台上显示不全或不兼容。为了解决这一问题,我使用了Python的Pillow库来裁剪图片,确保它们符合闲鱼平台对于4:3图片比例的要求。通过编写脚本自动调整图片的尺寸,把调整好的图片上传到七牛云并获取返回的URL链接。这些链接随后被集成到商品信息中,确保了在闲鱼平台上的顺利显示。因为这个发布商品的接口不支持本地图片所以只能饶那么一大圈。
上架商品代码
import hashlib
import http.client
import json
import time
import csv
from PIL import Image
import requests
from qiniu import Auth, put_file, etag
import qiniu.config
import os
# 闲鱼应用配置
appKey = # 开放平台提供的应用KEY
appSecret = "" # 开放平台提供的应用密钥
domain = "" # 正式环境域名
# 七牛云配置
access_key = ''
secret_key = ''
bucket_name = '' # 请替换为您的存储空间名称
qiniu_domain = ''
# 初始化Auth状态
q = Auth(access_key, secret_key)
def upload_to_qiniu(local_file, remote_file):
"""
上传文件到七牛云
:param local_file: 本地文件路径
:param remote_file: 上传到七牛后保存的文件名
:return: 上传后的文件URL
"""
token = q.upload_token(bucket_name, remote_file, 3600)
ret, info = put_file(token, remote_file, local_file)
if ret is not None:
return f'http://{qiniu_domain}/{remote_file}'
else:
print(info) # 输出错误信息
return None
# 签名函数
def genSign(bodyJson: str, timestamp: int):
"""
生成请求的签名。
:param bodyJson: 请求体的JSON字符串
:param timestamp: 当前时间戳
:return: 签名字符串
"""
m = hashlib.md5()
m.update(bodyJson.encode("utf8"))
bodyMd5 = m.hexdigest()
s = f"{appKey},{bodyMd5},{timestamp},{appSecret}"
m = hashlib.md5()
m.update(s.encode("utf8"))
sign = m.hexdigest()
return sign
# 请求函数
def request(url: str, data: json):
"""
发送POST请求到指定的URL。
:param url: API的URL路径
:param data: 请求体数据(字典)
:return: API的响应
"""
body = json.dumps(data, separators=(",", ":"))
timestamp = int(time.time())
sign = genSign(body, timestamp)
url = f"{domain}{url}?appid={appKey}×tamp={timestamp}&sign={sign}"
headers = {"Content-Type": "application/json"}
conn = http.client.HTTPSConnection("api.goofish.pro")
conn.request("POST", url, body, headers)
res = conn.getresponse()
reps = res.read().decode("utf-8")
return reps
# 创建商品函数
def create_product(product_data):
"""
创建商品。
:param product_data: 商品数据
:return: 创建商品的API响应
"""
return request("/api/open/product/create", product_data)
def download_and_resize_image(url, local_path, target_aspect=4/3):
response = requests.get(url)
if response.status_code == 200:
with open(local_path, 'wb') as file:
file.write(response.content)
with Image.open(local_path) as img:
original_width, original_height = img.size
new_width = int(original_height * target_aspect) if original_width < original_height else original_width
new_height = int(new_width / target_aspect)
img_resized = img.resize((new_width, new_height), Image.ANTIALIAS)
img_resized.save(local_path)
# 读取CSV文件并创建商品
def create_products_from_csv(csv_file):
with open(csv_file, mode='r', encoding='utf-8') as file:
csv_reader = csv.reader(file)
next(csv_reader) # 跳过标题行
i=999
for row in csv_reader:
i+=1
title, price, image_url = row
modified_price = int((float(price) - 1) * 100) # 价格减1元后转换为分
local_image_path = f'{i}.png'
download_and_resize_image(image_url, local_image_path, 4/3)
# 上传到七牛云并获取URL
time.sleep(1)
qiniu_url = upload_to_qiniu(local_image_path, local_image_path)
print(qiniu_url)
time.sleep(1)
product_data = {
"item_biz_type": 2, # 示例:2普通商品
"sp_biz_type": 1, # 示例:1手机
"channel_cat_id": "", # 示例类目ID
"channel_pv": [
{"property_id": "0", "property_name": "0", "value_id": "0", "value_name": "0"}
],
"price": modified_price, # 假设CSV中的价格是以元为单位
"stock": 10, # 示例库存
"express_fee": 0, # 示例运费
"publish_shop": [
{
"user_name": "会员名",
"province": 110000,
"city": 110100,
"district": 110101,
"title": f'【2024红包封面】- {title}',
"content": f'标价就是卖价 - {title} - 红包封面序列号新款 2024\n拍下发序列号,可以使用 3 个月,有喜欢的款式可以直接下单,全天自动发货\n说明:因商品具有一次性激活,故该产品一旦售出,不退不换,谢谢谅解', # 假设内容和标题相同
"images": [qiniu_url]
}
],
# 其他必填字段...
}
response = create_product(product_data)
print(response)
# 调用函数,读取CSV文件并创建商品
csv_file = 'products.csv' # 替换为CSV文件的路径
create_products_from_csv(csv_file)
4. 高效率的成果
最终,这个工具令结果满意的。在几分钟内,我成功地将三个账号中的共计1000多个商品批量上架到闲鱼。