一、接口分析
Daraz平台未公开官方API文档,但可通过分析网络请求获取数据接口。核心步骤如下:
请求URL
搜索页面的数据接口通常为:base_url = "https://www.daraz.pk/api/catalog/search"关键参数
params = { "q": "mobile", # 搜索关键词 "page": 1, # 分页页码 "sort": "popularity", # 排序方式 "spm": "a2a0e.12345678" # 页面标识(需动态获取) }请求头要求
需模拟浏览器行为防止反爬:headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)", "Referer": "https://www.daraz.pk/" }
二、Python实现示例
import requests import json def fetch_daraz_search(keyword, page=1): url = "https://www.daraz.pk/api/catalog/search" # 动态获取spm参数(需实际抓取页面源码解析) spm_value = extract_spm() params = { "q": keyword, "page": page, "sort": "popularity", "spm": spm_value } headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)", "Accept-Language": "en-US,en;q=0.9" } try: response = requests.get(url, params=params, headers=headers) if response.status_code == 200: return response.json() # 返回结构化JSON数据 else: print(f"请求失败,状态码:{response.status_code}") except Exception as e: print(f"接口异常:{str(e)}") # 示例调用 data = fetch_daraz_search("wireless earphones", page=2) print(json.dumps(data, indent=2))三、返回数据结构解析
典型响应数据包含:
{ "data": { "products": [ { "id": "P0012345", "name": "Wireless Bluetooth Earbuds", "price": "Rs. 1,299", "original_price": "Rs. 2,599", "rating": 4.5, "review_count": 128 }, // ... 其他商品数据 ], "total_pages": 23 // 总页数 } }四、注意事项
反爬策略
- 使用代理IP轮询(推荐
requests.Session+代理池) - 添加随机延迟:
time.sleep(random.uniform(1, 3)) - 定期更新User-Agent
- 使用代理IP轮询(推荐
参数动态性
spm参数需从页面HTML中实时提取:def extract_spm(): # 示例:从首页<script>标签中正则匹配 pattern = r'"spm":"([a-z0-9\.]+)"' # 实际需通过请求首页获取法律合规
! 重要:请遵守Daraz的robots.txt限制,避免高频请求(建议≤5次/分钟)
五、扩展方案
若API变动频繁,可采用浏览器自动化方案:
from selenium import webdriver from selenium.webdriver.common.by import By driver = webdriver.Chrome() driver.get("https://www.daraz.pk/search?q=mobile") # 直接解析页面DOM获取数据 product_elements = driver.find_elements(By.CSS_SELECTOR, "div.product-card")通过此方法可实现更稳定的数据采集,但需权衡性能与维护成本。