使用 Python 进行速卖通数据采集主要有官方 API 调用(合规优先)和网页爬虫(补充方案)两种方式,以下是具体实现步骤、代码示例及注意事项:

一、方式一:官方 API 调用(推荐,合规稳定)

速卖通开放平台提供标准化 API 接口,需先完成开发者认证并获取密钥,再通过 Python 发送请求获取结构化数据。

1. 前期准备

  1. 注册开发者账号:访问速卖通,完成企业 / 个人认证,创建应用并获取appKeyappSecret
  2. 申请接口权限:在开放平台申请目标接口(如商品详情、搜索接口),部分接口需审核。
  3. 了解接口文档:参考速卖通API文档,明确接口参数、签名规则及返回格式。

2. Python 实现 API 调用(以商品详情接口为例)

核心步骤:生成签名 → 构造请求 → 解析响应

python

运行

import requests
import hashlib
import time
import json

# 配置参数(替换为你的实际信息)
APP_KEY = "你的appKey"
APP_SECRET = "你的appSecret"
PRODUCT_ID = "商品ID(如1005006234567890)"
API_METHOD = "aliexpress.item.get"  # 商品详情接口
TIMESTAMP = str(int(time.time() * 1000))  # 毫秒级时间戳

# 1. 构造请求参数(需按字母排序用于签名)
params = {
    "appKey": APP_KEY,
    "method": API_METHOD,
    "productId": PRODUCT_ID,
    "timestamp": TIMESTAMP,
    "format": "json",
    "v": "2.0"
}

# 2. 生成签名(速卖通API签名规则:排序参数拼接+appSecret后MD5加密)
sorted_params = sorted(params.items(), key=lambda x: x[0])
sign_str = "&".join([f"{k}={v}" for k, v in sorted_params]) + APP_SECRET
sign = hashlib.md5(sign_str.encode("utf-8")).hexdigest().upper()
params["sign"] = sign

# 3. 发送POST请求
url = "https://gw.api.alibaba.com/openapi/param2/1/aliexpress.open/api"
response = requests.post(url, data=params)

# 4. 解析响应数据
if response.status_code == 200:
    result = response.json()
    if "error_response" not in result:
        # 提取商品核心信息
        item = result["result"]["product"]
        product_info = {
            "商品ID": item.get("productId"),
            "标题": item.get("subject"),
            "价格": item.get("salePrice"),
            "销量": item.get("tradeCount"),
            "库存": item.get("stock"),
            "好评率": item.get("positiveFeedbackRate"),
            "主图": item.get("imageUrl")
        }
        print(json.dumps(product_info, ensure_ascii=False, indent=2))
    else:
        print(f"API调用失败:{result['error_response']['msg']}")
else:
    print(f"请求失败,状态码:{response.status_code}")

3. 常用 API 接口示例

  • 商品搜索接口aliexpress.item_search(关键词 / 类目搜索商品列表)
  • 评论接口aliexpress.product.review.query(获取商品评论)
  • 店铺商品接口aliexpress.seller.item.list(获取店铺所有商品)

二、方式二:网页爬虫(无 API 权限时使用)

若无法获取 API 权限,可通过 Python 爬虫抓取速卖通网页数据,但需注意反爬机制和合规风险。

1. 静态页面爬取(requests + BeautifulSoup)

适用于简单页面(如商品列表页),需分析网页结构定位元素。

示例:爬取速卖通搜索结果页商品信息

python

运行

import requests
from bs4 import BeautifulSoup
import time

# 配置请求头(模拟浏览器,避免被识别为爬虫)
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    "Accept-Language": "en-US,en;q=0.9",
    "Referer": "https://www.aliexpress.com/"
}

def crawl_search_results(keyword, page=1):
    url = f"https://www.aliexpress.com/w/wholesale-{keyword}.html?page={page}"
    try:
        # 发送请求(添加延迟,避免频繁请求)
        response = requests.get(url, headers=headers, timeout=10)
        response.encoding = "utf-8"
        soup = BeautifulSoup(response.text, "html.parser")
        
        # 定位商品卡片(需根据网页结构调整Selector)
        products = soup.select(".product-card-item")
        data = []
        for product in products:
            try:
                item = {
                    "标题": product.select_one(".product-title").get_text(strip=True) if product.select_one(".product-title") else None,
                    "价格": product.select_one(".product-price").get_text(strip=True) if product.select_one(".product-price") else None,
                    "销量": product.select_one(".product-sale-count").get_text(strip=True) if product.select_one(".product-sale-count") else None,
                    "商品链接": "https://www.aliexpress.com" + product.select_one("a").get("href") if product.select_one("a") else None
                }
                data.append(item)
            except Exception as e:
                print(f"解析商品失败:{e}")
                continue
        return data
    except Exception as e:
        print(f"请求失败:{e}")
        return []

# 调用示例:爬取“wireless earphones”第1页数据
results = crawl_search_results("wireless earphones", page=1)
for item in results[:5]:  # 打印前5条
    print(item)

2. 动态页面爬取(Selenium/Playwright)

速卖通详情页大量使用 JavaScript 动态加载(如价格、库存、评价),需用自动化工具模拟浏览器渲染。

示例:用 Selenium 爬取商品详情页

python

运行

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

def crawl_product_detail(product_url):
    # 配置Chrome选项(无头模式,不显示浏览器窗口)
    options = webdriver.ChromeOptions()
    options.add_argument("--headless=new")
    options.add_argument("--no-sandbox")
    options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
    
    driver = webdriver.Chrome(options=options)
    try:
        driver.get(product_url)
        # 等待价格元素加载(最多等待10秒)
        price = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, ".product-price-current"))
        ).text
        # 提取其他信息
        title = driver.find_element(By.CSS_SELECTOR, ".product-title-text").text
        sales = driver.find_element(By.CSS_SELECTOR, ".product-reviewer-sold").text
        specs = [spec.text for spec in driver.find_elements(By.CSS_SELECTOR, ".product-specs-item")]
        
        return {
            "标题": title,
            "价格": price,
            "销量": sales,
            "规格": specs
        }
    except Exception as e:
        print(f"爬取详情失败:{e}")
        return None
    finally:
        driver.quit()

# 调用示例(替换为实际商品链接)
product_url = "https://www.aliexpress.com/item/1005006234567890.html"
detail = crawl_product_detail(product_url)
print(detail)

三、数据存储与处理

采集到的数据可存储为 CSV/Excel 或数据库,方便后续分析:

1. 存储为 CSV 文件

python

运行

import csv

# 假设results是采集到的商品列表数据
with open("aliexpress_products.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=["标题", "价格", "销量", "商品链接"])
    writer.writeheader()
    writer.writerows(results)

2. 存储到 MySQL 数据库

python

运行

import pymysql

# 连接数据库(替换为你的配置)
conn = pymysql.connect(
    host="localhost",
    user="root",
    password="your_password",
    database="aliexpress_data"
)
cursor = conn.cursor()

# 创建表(首次运行)
cursor.execute("""
CREATE TABLE IF NOT EXISTS products (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(500),
    price VARCHAR(50),
    sales VARCHAR(50),
    url VARCHAR(500)
)
""")

# 插入数据
for item in results:
    cursor.execute("""
    INSERT INTO products (title, price, sales, url)
    VALUES (%s, %s, %s, %s)
    """, (item["标题"], item["价格"], item["销量"], item["商品链接"]))

conn.commit()
conn.close()

四、反爬与合规注意事项

  1. API 调用限制:遵守速卖通 API 的调用频率限制(通常 100 次 / 分钟),避免滥用导致账号封禁。
  2. 爬虫反爬策略
    • 使用代理 IP 池(如阿布云、快代理)避免 IP 被封;
    • 随机 User-Agent、添加请求延迟(1-3 秒 / 次);
    • 避免爬取用户敏感信息(如手机号、邮箱)。
  3. 合规风险:爬虫可能违反速卖通用户协议,仅用于个人学习或内部分析,禁止商用或大规模爬取。
  4. 动态反爬应对:若遇到验证码,可使用第三方打码平台(如超级鹰)或调整爬虫策略。

五、进阶优化

  • 使用 Scrapy 框架:适合大规模爬取,支持分布式、自动重试、数据管道等功能。
  • 异步请求:用aiohttp替代requests,提升爬取效率。
  • 数据清洗:通过正则表达式、文本处理库(如jieba)清洗脏数据,提取关键信息。

通过以上方法,可实现速卖通商品数据的高效采集,优先推荐官方 API 确保合规,爬虫仅作为补充方案。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐