一、前置准备
本次实操无需复杂环境,仅需准备Windows/Mac/Linux任意系统,提前完成以下2步基础配置:
1. 安装Python3.8+环境
- Windows/Mac用户:直接访问Python官网下载页 https://www.python.org/downloads/,选择最新稳定版(推荐3.11.9),安装时务必勾选Add Python to PATH,默认下一步即可
- Linux用户(以Ubuntu/Debian为例):执行以下命令:
```bash
sudo apt update
sudo apt install python3 python3-pip -y
```
2. 安装必要第三方库
打开终端(Windows用CMD/PowerShell,Mac/Linux用Terminal),依次执行2条pip命令:
```bash
pip install requests pandas openpyxl
pip install fake-useragent
```
二、数据爬取核心逻辑说明
京东未直接开放单商品/全品类实时销售额API,但价格、评论数、销量段标签(如“5000+人付款”)可从商品列表页公开获取,本次实操将爬取销量段标签并按“标签数值×客单价区间中位数”估算品类销售额(客单价区间中位数可提前从商品列表页的价格分布手动统计或用后续筛选逻辑计算),以手机品类为例演示。
三、实操代码全解析(可直接复制运行)
创建一个名为jd_sales_crawler.py的文件,粘贴以下完整代码:
```python
import requests
import pandas as pd
import time
import random
from fake_useragent import UserAgent
from urllib.parse import quote
配置区——可修改!
CATEGORY = "手机" 目标品类
MAX_PAGE = 5 爬取最大页数(单页约30个商品,过多可能触发验证码)
PRICE_RANGE = [1000, 10000] 目标价格区间(避免干扰品)
SALES_MAPPING = { 销量段标签→估算数值(可根据品类调整)
"100+": 150,
"500+": 750,
"1000+": 1500,
"2000+": 3000,
"5000+": 7500,
"1万+": 15000,
"2万+": 30000,
"5万+": 75000,
"10万+": 150000,
"50万+": 750000,
"100万+": 1500000
}
ua = UserAgent()
session = requests.Session()
def get_jd_products():
products = []
encoded_category = quote(CATEGORY)
for page in range(1, MAX_PAGE + 1):
print(f"正在爬取第{page}页...")
京东商品列表页接口(仅公开可访问部分数据,无需登录)
url = f"https://search.jd.com/Search?keyword={encoded_category}&wq={encoded_category}&pvid={random.randint(1000000000,9999999999)}&page={2page-1}&s={30(page-1)+1}&click=0"
headers = {
"User-Agent": ua.random,
"Referer": "https://www.jd.com/",
"Accept-Language": "zh-CN,zh;q=0.9",
"Accept-Encoding": "gzip, deflate, br",
"Connection": "keep-alive"
}
try:
response = session.get(url, headers=headers, timeout=10)
response.encoding = 'utf-8'
html = response.text
解析核心数据:商品名、价格、销量段标签
这里用基础字符串切割(无需安装lxml/bs4,降低门槛)
item_blocks = html.split('
')
for block in item_blocks[1:]:
try:
提取价格
price_str = block.split('¥')[1].split('')[0].split(' ')[0]
price = float(price_str)
if not (PRICE_RANGE[0] <= price <= PRICE_RANGE[1]):
continue
提取销量段标签
sales_label = block.split('')[1].split('')[0].strip()
if sales_label not in SALES_MAPPING:
continue
提取简化商品名
name = block.split('
')[1].split('')[0].replace('
', '').replace('', '').strip()
估算单商品日常付款量(按销量段中位数×0.05,模拟1周的日常销量,可调整系数)
weekly_sales = SALES_MAPPING[sales_label] 0.05
估算单商品日常销售额
weekly_sales_amount = round(price weekly_sales, 2)
products.append({
"商品名": name,
"价格(元)": price,
"销量段标签": sales_label,
"估算周销量": round(weekly_sales, 0),
"估算周销售额(元)": weekly_sales_amount
})
except Exception as e:
continue
随机休眠3-8秒,避免触发反爬
time.sleep(random.uniform(3, 8))
except Exception as e:
print(f"第{page}页爬取失败:{e}")
continue
return products
def analyze_and_save(products):
if not products:
print("未获取到有效数据,请检查配置或稍后再试")
return
df = pd.DataFrame(products)
简易分析:TOP10周销售额商品、品类总估算周销售额、平均客单价
top10 = df.sort_values(by="估算周销售额(元)", ascending=False).head(10)
total_sales = round(df["估算周销售额(元)"].sum(), 2)
avg_price = round(df["价格(元)"].mean(), 2)
保存数据到Excel
with pd.ExcelWriter(f"{CATEGORY}_京东估算周销售额.xlsx", engine="openpyxl") as writer:
df.to_excel(writer, sheet_name="全部商品", index=False)
top10.to_excel(writer, sheet_name="TOP10销售额", index=False)
写入分析汇总表
summary_data = [
["指标", "数值"],
["品类总估算周销售额(元)", total_sales],
["平均客单价(元)", avg_price],
["有效商品数", len(df)]
]
summary_df = pd.DataFrame(summary_data[1:], columns=summary_data[0])
summary_df.to_excel(writer, sheet_name="分析汇总", index=False)
print(f"分析完成!数据已保存到【{CATEGORY}_京东估算周销售额.xlsx】")
print(f"品类总估算周销售额:{total_sales}元")
print(f"平均客单价:{avg_price}元")
print(f"有效商品数:{len(df)}")
if __name__ == "__main__":
products = get_jd_products()
analyze_and_save(products)
```
四、代码关键配置说明(零门槛调整)
1. 基础参数修改
- CATEGORY:替换为你想爬取的任意品类(如“笔记本电脑”“洗发水”“空气炸锅”)
- MAX_PAGE:建议首次测试设为2-3页,确定正常后再增至5-10页(超过10页大概率触发京东滑块验证码,暂不提供滑块破解方法)
- PRICE_RANGE:只保留区间内的有效商品,比如爬取“高端洗发水”可设为[80, 300]
- SALES_MAPPING:根据品类销量规模调整中位数,比如冷门品类“工业游标卡尺”可将“1万+”设为12000而非15000
2. 日常销量系数调整

代码中weekly_sales = SALES_MAPPING[sales_label] 0.05的0.05是模拟1周日常销量的系数:
- 京东“X人付款”标签是累计近30天付款人数,日常非大促期间,周销量约为30天的1/5-1/7,取中间值0.05(即20天的销量)
- 大促前1周可设为0.1,大促后1周可设为0.02
五、常见卡壳问题解决方案
1. 安装fake-useragent失败
执行以下命令使用国内镜像源安装:
```bash
pip install fake-useragent -i https://pypi.tuna.tsinghua.edu.cn/simple
```
2. 爬取所有页面失败
检查以下3点:
- 确认电脑能正常访问京东官网
- 将代码中的ua.random替换为固定的浏览器User-Agent(复制当前Chrome浏览器的User-Agent:Chrome地址栏输入chrome://version/,找到“用户代理”复制)
- 将随机休眠时间random.uniform(3, 8)增至random.uniform(8, 15)
3. 生成的Excel文件打不开
确认已安装openpyxl库,或用国内镜像源重新安装:
```bash
pip install openpyxl -i https://pypi.tuna.tsinghua.edu.cn/simple
```
六、简易数据验证方法
爬取完成后可打开Excel的“全部商品”表,随机挑选3-5个TOP商品:
- 访问该商品详情页,查看累计评价数(京东商品累计评价数约为累计付款人数的1/3-1/10)
- 用累计评价数×5(取中间比例)得到估算30天付款人数
- 与代码中SALES_MAPPING[sales_label]对比,误差在2倍以内均合理
相关推荐