本文针对 Shopee 平台商品数据抓取中常见的反爬拦截、效率低下、重复请求三大痛点,总结了经过生产验证的 3 大核心要点。适用于跨境选品、竞品分析、价格监控等场景
一、URL 结构与 ID 快速提取
Shopee 全球所有站点采用完全统一的商品 URL 设计,无需针对不同地区单独适配解析逻辑,这是实现批量自动化抓取的基础。
1.全球通用 URL 格式
标准商品 URL 结构:
https://{
地区代码}.shopee.com/product/{
店铺ID}/{
商品ID}
常见地区代码:tw (中国台湾)、sg (新加坡)、my (马来西亚)、th (泰国)、id (印尼)、ph (菲律宾)、vn (越南)
兼容性:支持带任意查询参数的 URL(如?spm=xxx&utm_source=yyy),不影响 ID 提取
示例:
import re
def get_shopee_ids(url: str) -> tuple[str | None, str | None]:
"""
从Shopee商品URL中提取店铺ID和商品ID
:param url: Shopee商品完整URL
:return: (店铺ID, 商品ID),解析失败返回(None, None)
"""
pattern = r'/product/(\d+)/(\d+)'
match = re.search(pattern, url)
return match.groups() if match else (None, None)
# 测试示例
if __name__ == "__main__":
# http://o0b.cn/alan
test_urls = [
"https://shopee.tw/product/123456789/987654321",
"https://shopee.sg/product/987654321/123456789?spm=a1z10.1-c-seller",
"https://invalid-url.com/product/abc/123"
]
for url in test_urls:
shop_id, item_id = get_shopee_ids(url)
print(f"URL: {url}")
print(f"店铺ID: {
shop_id}, 商品ID:
二、必带核心请求头
Shopee 的反爬系统对请求头校验极为严格,只需配置以下 5 个核心请求头,即可绕过 90% 以上的基础拦截,其余非必要头字段可全部省略,减少请求体积
基础商品页面请求示例
from curl_cffi import requests
import random
import time
session = requests.Session(
headers={
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/125.0.0.0 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "zh-TW,zh;q=0.9",
"Referer": "https://shopee.tw/",
"Cookie": "粘贴你浏览器里的完整 Cookie",
},
impersonate="chrome101",
)
# http://o0b.cn/alan
urls = [
"https://shopee.tw/product/123456789/987654321",
"https://shopee.tw/product/123456789/123456789",
]
for url in urls:
r = session.get(url, timeout=10)
print(url, r.status_code)
time.sleep(random.uniform(1.2, 2.5))
三、ETag 缓存校验
Shopee 使用MD5 哈希值作为 ETag 实体标签,唯一标识商品页面的特定版本。通过缓存校验机制,可避免重复下载未变化的页面内容,对于价格、库存等更新频率较低的字段,能提升 90% 以上的抓取效率,同时大幅降低被平台的风险。
ETag 生成规则
若因特殊情况无法获取服务器返回的 ETag,可使用 Shopee 官方规则自行计算
import hashlib
def generate_etag(shop_id: str, item_id: str) -> str:
"""根据Shopee官方规则生成备用ETag"""
raw = f"{shop_id}_{item_id}".encode("utf-8")
return f'"{hashlib.md5(raw).hexdigest()}"'
带缓存的请求代码
from typing import Dict, Tuple
import requests
import hashlib
cache: Dict[str, Tuple[str, str]] = {
}
def get_shopee_ids(url: str) -> Tuple[str, str]:
parts = url.split('/')
for i, part in enumerate(parts):
if part == 'product' and i + 2 < len(parts):
return parts[i+1], parts[i+2]
return '', ''
def get_common_headers(region: str, cookie: str) -> dict:
return {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
"Cookie": cookie,
"Referer": f"https://{region}.shopee.com/",
"Accept-Encoding": "gzip, deflate, br",
"Connection": "keep-alive",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "zh-TW,zh;q=0.9,en;q=0.8"
}
def generate_etag(shop_id: str, item_id: str) -> str:
return hashlib.md5(f"{shop_id}_{item_id}".encode()).hexdigest()
def fetch_shopee_with_cache(url: str, cookie: str) -> str:
shop_id, item_id = get_shopee_ids(url)
if not shop_id or not item_id:
raise ValueError("无效的Shopee商品URL")
cache_key = f"{shop_id}_{item_id}"
region = url.split('.')[0].split('//')[-1]
headers = get_common_headers(region, cookie)
if cache_key in cache:
cached_etag, cached_content = cache[cache_key]
headers["If-None-Match"] = cached_etag
response = requests.get(url, headers=headers, timeout=10)
if response.status_code == 304:
print(f"[缓存命中] {cache_key} 资源未变化,使用本地缓存")
return cached_content
elif response.status_code == 200:
etag = response.headers.get("ETag", generate_etag(shop_id, item_id))
content = response.text
cache[cache_key] = (etag, content)
print(f"[缓存更新] {cache_key} 资源已更新,缓存已刷新")
return content
else:
response.raise_for_status()
if __name__ == "__main__":
MY_COOKIE = "替换为你的Shopee Cookie(从浏览器复制完整Cookie字符串)"
test_url = "https://shopee.tw/product/123456789/987654321"
try:
content1 = fetch_shopee_with_cache(test_url, MY_COOKIE)
print(f"第一次请求内容长度: {len(content1)} 字符\n")
content2 = fetch_shopee_with_cache(test_url, MY_COOKIE)
print(f"第二次请求内容长度: {len(content2)} 字符\n")
assert content1 == content2, "缓存内容与原始内容不一致"
print("缓存校验成功,两次请求内容完全一致")
except Exception as e:
print(f"请求失败: {str(e)}")
四、避坑指南
Cookie 获取与更新:从浏览器开发者工具 Network 面板,任意 Shopee 页面请求的 Cookie 中复制SPC_EC和SPC_U字段,有效期通常为 1-2 周,过期后需重新获取
请求频率控制:建议单 IP 每秒请求不超过 1 次,批量抓取时添加random.uniform(0.5, 1.5)随机延迟,避免触发 IP 封禁
地区一致性:请求头中的 Referer 必须与 URL 中的地区代码完全一致,否则会被重定向或拦截
动态内容处理:商品实时价格、库存、销量等数据通过 AJAX 接口加载,需单独请求接口获取
异常处理:添加重试机制(使用tenacity库),针对 429(请求过多)、503(服务不可用)等错误进行指数退避重试