Python采集闲鱼商品详情并返回JSON数据全攻略
引言
在二手交易平台中,闲鱼拥有海量商品信息。通过Python采集这些数据并结构化输出为JSON格式,可实现商品监控、价格分析、竞品调研等应用。本文将详细解析三种主流采集方案,并提供可直接运行的代码示例。
方案一:API接口直连(推荐)
实施步骤
获取API密钥
- 注册阿里开放平台账号,创建应用获取
app_key
和app_secret
- 申请闲鱼商品详情API权限(需企业认证)
- 注册阿里开放平台账号,创建应用获取
构造请求参数
import requests
import hashlib
import time
app_key = "YOUR_APP_KEY"
app_secret = "YOUR_APP_SECRET"
item_id = "1234567890" # 商品ID
# 生成签名
def generate_sign(params, secret):
sorted_params = sorted(params.items())
sign_str = secret + "".join(f"{k}{v}" for k,v in sorted_params) + secret
return hashlib.md5(sign_str.encode()).hexdigest().upper()
# 构建请求
url = "https://api.xianyu.com/item/detail"
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
params = {
"app_key": app_key,
"item_id": item_id,
"timestamp": timestamp
}
params["sign"] = generate_sign(params, app_secret)
处理响应数据
response = requests.get(url, params=params)
if response.status_code == 200:
data = response.json()
# 提取核心字段
item_data = {
"title": data["data"]["title"],
"price": float(data["data"]["price"]),
"description": data["data"]["description"],
"images": data["data"]["images"],
"seller": data["data"]["seller"]["nick"]
}
# 生成JSON
json_output = json.dumps({"status": "success", "data": item_data}, ensure_ascii=False, indent=2)
print(json_output)
优势
- 数据结构规范,无需解析HTML
- 更新频率稳定,兼容性佳
- 支持批量数据获取
方案二:动态页面解析(备选)
适用场景
无API权限时的替代方案,需处理动态加载内容
技术实现
from selenium import webdriver |
from selenium.webdriver.chrome.options import Options |
import time |
# 配置无头浏览器 |
chrome_options = Options() |
chrome_options.add_argument("--headless") |
driver = webdriver.Chrome(options=chrome_options) |
# 模拟访问商品详情页 |
url = "https://detail.xianyu.com/item.htm?id=1234567890" |
driver.get(url) |
time.sleep(3) # 等待页面加载 |
# 提取商品信息 |
title = driver.find_element("xpath", '//h1[@class="title-main"]').text |
price = driver.find_element("xpath", '//span[@class="price-main"]').text |
description = driver.find_element("xpath", '//div[@class="desc-content"]').text |
# 关闭浏览器 |
driver.quit() |
反爬处理技巧
- 随机User-Agent轮换
- 代理IP池使用
- 请求间隔随机化
- Cookie池管理
方案三:网络请求直抓(基础)
基础代码框架
import requests |
from bs4 import BeautifulSoup |
import json |
headers = { |
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" |
} |
response = requests.get("https://s.2.taobao.com/search?q=手机", headers=headers) |
soup = BeautifulSoup(response.text, 'html.parser') |
products = [] |
for item in soup.select('.item-container'): |
products.append({ |
"title": item.select_one('.title').text.strip(), |
"price": item.select_one('.price').text, |
"link": item.select_one('a')['href'] |
}) |
# 生成JSON |
with open('products.json', 'w', encoding='utf-8') as f: |
json.dump(products, f, ensure_ascii=False, indent=2) |
数据处理与存储
JSON数据结构示例
{ |
"status": "success", |
"data": { |
"title": "iPhone 13 Pro Max", |
"price": 5899.00, |
"description": "99新,无拆修,带原装充电器", |
"images": [ |
"https://img.xianyu.com/item/1234567890_1.jpg", |
"https://img.xianyu.com/item/1234567890_2.jpg" |
], |
"seller": "数码专家" |
} |
} |
存储方案对比
存储方式 | 适用场景 | 优势 |
---|---|---|
JSON文件 | 小数据量 | 格式统一,跨平台兼容 |
数据库 | 持续采集 | 支持查询,数据持久化 |
CSV文件 | 表格数据 | 便于Excel处理 |
总结
本文提供了三种闲鱼商品采集方案,其中API直连方案最为稳定高效,动态解析方案适用于无API权限场景,基础网络请求方案适合快速验证。实际使用时需根据具体需求选择方案,并严格遵守平台规则和法律法规。通过合理的数据采集和处理,可构建高效的二手商品监控系统,为商业决策提供数据支持。