最近在分析电商市场趋势时,经常需要批量获取商品数据。传统手动记录方式效率低下,而市面上的数据分析工具又往往价格昂贵。于是我用Python开发了一套淘宝商品数据采集与可视化系统,能够自动抓取商品信息并生成直观的数据报表。
这个系统特别适合以下几类人群:
系统采用三层架构设计:
选择这些库的主要考虑:
淘宝的反爬机制比较严格,我们采用了以下对策:
python复制def get_product_info(keyword, pages=3):
headers = {
'User-Agent': random.choice(USER_AGENTS),
'Cookie': '你的cookie'
}
product_list = []
for page in range(1, pages+1):
url = f"https://s.taobao.com/search?q={keyword}&s={(page-1)*44}"
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
items = soup.select('.item.J_MouserOnverReq')
for item in items:
product = {
'title': item.select('.title')[0].text.strip(),
'price': item.select('.price')[0].text.strip(),
'sales': item.select('.deal-cnt')[0].text.strip(),
'shop': item.select('.shop')[0].text.strip(),
'location': item.select('.location')[0].text.strip()
}
product_list.append(product)
time.sleep(random.uniform(2,5))
return pd.DataFrame(product_list)
采集的原始数据需要经过以下处理:
python复制def clean_data(df):
# 价格清洗
df['price'] = df['price'].str.extract(r'(\d+\.?\d*)').astype(float)
# 销量清洗
df['sales_num'] = df['sales'].apply(lambda x:
float(x.replace('人收货','').replace('万+','0000'))
if '万+' in x else float(x.replace('人收货','')))
# 去重
df = df.drop_duplicates(subset=['title','shop'])
return df
python复制def plot_price_distribution(df):
plt.figure(figsize=(10,6))
sns.histplot(df['price'], bins=30, kde=True)
plt.title('商品价格分布')
plt.xlabel('价格(元)')
plt.ylabel('商品数量')
plt.grid(True)
plt.savefig('price_dist.png')
python复制def plot_top_products(df):
top10 = df.nlargest(10, 'sales_num')
bar = (
Bar()
.add_xaxis(top10['title'].tolist())
.add_yaxis("销量", top10['sales_num'].tolist())
.set_global_opts(
title_opts=opts.TitleOpts(title="销量TOP10商品"),
xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=-45))
)
)
bar.render("top10_sales.html")
注意:遇到"您的访问过于频繁"提示时,应该:
- 立即停止程序
- 更换IP地址
- 增加请求间隔时间
- 检查Cookie是否失效
其他常见问题:
推荐两种部署方式:
开发和使用爬虫时务必注意:
这个项目我从最初版本到现在已经迭代了5个版本,最大的体会是:淘宝的反爬策略会不定期更新,需要持续维护代码。建议每两周测试一次核心功能,及时发现和解决问题。对于需要长期监控的商品,可以考虑将程序部署到云服务器上自动运行。