Python爬取商品数据,如何自动化分析竞争对手?
在电商行业,竞争对手分析是非常重要的一项工作。而爬取商品数据并进行自动化分析是提高效率的重要手段。本文将介绍如何使用Python爬取商品数据,并通过自动化分析竞争对手,进一步优化业务。
1. 爬取商品数据
爬取商品数据是竞争对手分析的基础,本文将以淘宝平台为例。
首先,我们需要在淘宝搜索框中输入关键字,例如“手机”,并获取搜索页面中的商品链接。具体实现如下:
```python
import requests
from bs4 import BeautifulSoup
# 搜索关键字
keyword = '手机'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
# 获取搜索页面链接
def get_search_url(keyword):
return 'https://s.taobao.com/search?q=' + keyword
# 获取搜索页面中的商品链接
def get_product_urls(keyword):
search_url = get_search_url(keyword)
html = requests.get(search_url, headers=headers).text
soup = BeautifulSoup(html, 'html.parser')
product_urls = []
for link in soup.select('a.J_ClickStat'):
product_urls.append(link['href'])
return product_urls
```
接下来,我们需要进入每个商品链接,获取商品的基本信息,并存储到数据库中。具体实现如下:
```python
import re
import pymongo
# 连接MongoDB数据库
client = pymongo.MongoClient('localhost', 27017)
db = client['taobao']
collection = db['product']
# 获取商品基本信息
def get_product_info(url):
html = requests.get(url, headers=headers).text
soup = BeautifulSoup(html, 'html.parser')
# 商品名称
title = soup.select_one('.tb-main-title').text.strip()
# 商品价格
price = float(soup.select_one('.tb-rmb-num').text)
# 商品销量
sales = int(re.findall(r'已售\d+', soup.select_one('.tb-sell-counter').text)[0][2:])
# 商品评价数
comments = int(re.findall(r'评价\d+', soup.select_one('.tb-rev-num').text)[0][2:])
# 商品评分
score = float(soup.select_one('.tb-rate-higher').text)
# 商品店铺名称
shop = soup.select_one('.tb-shop-name').text.strip()
# 商品链接
url = url
product = {'title': title, 'price': price, 'sales': sales, 'comments': comments, 'score': score, 'shop': shop, 'url': url}
return product
# 爬取商品数据并存储到数据库
def crawl(keyword):
product_urls = get_product_urls(keyword)
for url in product_urls:
product = get_product_info(url)
collection.insert_one(product)
```
现在,我们已经成功爬取了指定关键字下所有商品的基本信息,并存储到了MongoDB数据库中。
2. 自动化分析竞争对手
基于所爬取的商品数据,我们可以进行一系列的自动化分析,例如:
- 获取所有竞争对手的店铺名称
- 统计每个竞争对手的商品数量、总销量、平均售价、平均评分等信息
- 对竞争对手的商品价格、销量、评分等指标进行排名
下面我们将逐一介绍如何实现这些功能。
2.1 获取所有竞争对手的店铺名称
我们可以通过MongoDB数据库中的数据,获取所有竞争对手的店铺名称。具体实现如下:
```python
# 获取所有竞争对手的店铺名称
def get_competitor_shops(keyword):
shops = []
for product in collection.find({'title': {'$regex': keyword}}, {'shop': 1}):
if product['shop'] not in shops:
shops.append(product['shop'])
return shops
```
2.2 统计每个竞争对手的商品数量、总销量、平均售价、平均评分等信息
我们可以根据店铺名称,筛选出属于每个竞争对手的商品数据,并计算相应的指标。具体实现如下:
```python
# 统计每个竞争对手的商品数量、总销量、平均售价、平均评分等信息
def get_competitor_stats(keyword):
stats = []
shops = get_competitor_shops(keyword)
for shop in shops:
products = list(collection.find({'title': {'$regex': keyword}, 'shop': shop}))
num_products = len(products)
total_sales = sum([product['sales'] for product in products])
avg_price = sum([product['price'] for product in products]) / num_products
avg_score = sum([product['score'] for product in products]) / num_products
stats.append({'shop': shop, 'num_products': num_products, 'total_sales': total_sales, 'avg_price': avg_price, 'avg_score': avg_score})
return stats
```
2.3 对竞争对手的商品价格、销量、评分等指标进行排名
我们可以通过pandas库的DataFrame对象,进行数据整理和排序,并使用matplotlib库进行数据可视化。具体实现如下:
```python
import pandas as pd
import matplotlib.pyplot as plt
# 对竞争对手的商品价格、销量、评分等指标进行排名
def plot_competitor_rank(keyword):
shops = get_competitor_shops(keyword)
data = []
for shop in shops:
products = list(collection.find({'title': {'$regex': keyword}, 'shop': shop}))
df = pd.DataFrame(products)
data.append({'shop': shop, 'df': df})
fig, axs = plt.subplots(3, figsize=(10, 8))
fig.suptitle('Ranking of Competitors')
axs[0].bar([d['shop'] for d in data], [d['df']['price'].mean() for d in data], color='blue')
axs[0].set_title('Avg. Price')
axs[1].bar([d['shop'] for d in data], [d['df']['sales'].sum() for d in data], color='red')
axs[1].set_title('Total Sales')
axs[2].bar([d['shop'] for d in data], [d['df']['score'].mean() for d in data], color='green')
axs[2].set_title('Avg. Score')
for ax in axs:
ax.tick_params(axis='x', labelrotation=45)
plt.show()
```
以上就是如何使用Python爬取商品数据,并通过自动化分析竞争对手的方法。通过爬取商品数据并对竞争对手进行分析,可以帮助我们更好地了解市场趋势和竞争对手的优劣势,从而制定更为有效的电商营销策略。