基于 Python 的美团外卖点餐数据分析:Flask 爬虫与可视化实战

前言

随着外卖行业的迅速发展,美团外卖已成为很多人日常生活中不可或缺的一部分。通过数据分析,我们可以挖掘出用户的消费习惯、热门餐品、配送时间等有价值的信息,为商家和用户提供更精准的推荐与服务。本文将展示如何通过 Flask 开发一个简单的爬虫,获取美团外卖平台的数据,并使用数据可视化技术对其进行分析。

我们将通过以下几个步骤实现:

Flask 爬虫: 获取美团外卖的餐品、价格、商家信息等数据。
数据清洗与分析: 使用 Pandas 对获取的数据进行处理与分析。
数据可视化: 通过 Matplotlib 和 ECharts 等工具展示分析结果。


一、技术栈与框架选择

Flask: 作为 Python 的轻量级 Web 框架,Flask 非常适合快速构建一个小型的 Web 应用。
requests + BeautifulSoup: 用于抓取美团外卖网站的数据。
Pandas: 用于数据清洗和分析。
Matplotlib/Plotly/ECharts: 用于生成数据可视化图表。
SQLite/MySQL: 用于存储爬取的数据(可以选择数据库进行数据持久化)。


二、Flask 项目初始化

首先,我们需要创建一个简单的 Flask 项目。

1. 创建虚拟环境并安装依赖
# 创建虚拟环境
python -m venv venv
# 激活虚拟环境
# Windows
venvScriptsactivate
# macOS/Linux
source venv/bin/activate

# 安装所需的库
pip install flask requests beautifulsoup4 pandas matplotlib
2. 创建 Flask 项目结构

项目结构如下:

/meituan_analysis
    /templates
        index.html
    /static
        /js
            chart.js
    app.py
    /scraper
        scraper.py

app.py:Flask 应用的主文件。
/scraper/scraper.py:用于爬取美团外卖数据的爬虫模块。
index.html:前端页面,展示爬取的数据和分析结果。


三、编写爬虫:获取美团外卖数据

/scraper/scraper.py 中,我们使用 requests 获取网页数据,并用 BeautifulSoup 解析网页,提取出美团外卖的餐品、商家信息和价格。

import requests
from bs4 import BeautifulSoup
import pandas as pd

def scrape_meituan():
    url = 'https://www.meituan.com/meishi/'
    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(url, headers=headers)
    soup = BeautifulSoup(response.text, 'html.parser')

    # 获取餐品信息
    items = []
    for item in soup.find_all('div', class_='poi-info'):
        name = item.find('h3').text.strip()
        price = item.find('span', class_='price').text.strip() if item.find('span', class_='price') else 'N/A'
        rating = item.find('span', class_='score').text.strip() if item.find('span', class_='score') else 'N/A'
        
        items.append({
            
            'name': name,
            'price': price,
            'rating': rating
        })

    # 转化为 Pandas DataFrame
    df = pd.DataFrame(items)
    return df

# 测试爬虫
if __name__ == '__main__':
    data = scrape_meituan()
    print(data)

这个爬虫将获取美团外卖网站上的餐品名称、价格、评分等信息,并将其保存在一个 Pandas DataFrame 中。

注意:

本示例使用的是美团外卖主页的一个页面,如果需要抓取更多数据,可能需要模拟翻页或者通过请求更多页面。
实际爬虫部署时,要遵守网站的 robots.txt 文件规范,以免造成不必要的压力。


四、数据清洗与分析

爬取到的数据可能包含一些不完整或者格式不规范的部分,需要通过 Pandas 进行数据清洗和处理。下面我们会处理一些常见的数据问题:

def clean_data(df):
    # 清洗价格:去除非数字字符
    df['price'] = df['price'].str.extract('(d+.d+)').astype(float)

    # 清洗评分:将评分为空的值设置为 NaN
    df['rating'] = pd.to_numeric(df['rating'], errors='coerce')

    # 填充缺失值:用列的平均值填充缺失值
    df['price'].fillna(df['price'].mean(), inplace=True)
    df['rating'].fillna(df['rating'].mean(), inplace=True)

    return df

# 清洗数据
cleaned_data = clean_data(data)
print(cleaned_data)
数据分析

我们可以对清洗后的数据进行一些简单的分析,比如:

餐品价格分布:查看价格的分布情况。
评分分布:查看餐品评分的分布情况。

import matplotlib.pyplot as plt

def plot_price_distribution(df):
    plt.figure(figsize=(10,6))
    plt.hist(df['price'], bins=30, color='blue', alpha=0.7)
    plt.title('Price Distribution of Dishes')
    plt.xlabel('Price (¥)')
    plt.ylabel('Frequency')
    plt.show()

def plot_rating_distribution(df):
    plt.figure(figsize=(10,6))
    plt.hist(df['rating'], bins=20, color='green', alpha=0.7)
    plt.title('Rating Distribution of Dishes')
    plt.xlabel('Rating')
    plt.ylabel('Frequency')
    plt.show()

# 可视化价格分布和评分分布
plot_price_distribution(cleaned_data)
plot_rating_distribution(cleaned_data)

五、Flask 后端与前端集成

现在我们将爬虫与 Flask 应用进行集成,用户可以通过 Flask 后端访问爬取的美团外卖数据并展示可视化图表。

1. 创建 Flask 应用

app.py 中,定义路由来处理前端请求,并返回分析结果。

from flask import Flask, render_template
from scraper.scraper import scrape_meituan, clean_data
import matplotlib.pyplot as plt
import io
import base64

app = Flask(__name__)

@app.route('/')
def index():
    # 爬取数据
    data = scrape_meituan()
    cleaned_data = clean_data(data)

    # 可视化分析结果
    fig, ax = plt.subplots(figsize=(10,6))
    ax.hist(cleaned_data['price'], bins=30, color='blue', alpha=0.7)
    ax.set_title('Price Distribution of Dishes')
    ax.set_xlabel('Price (¥)')
    ax.set_ylabel('Frequency')

    # 将图表转换为 Base64 编码格式,以便在网页中显示
    img = io.BytesIO()
    plt.savefig(img, format='png')
    img.seek(0)
    plot_url = base64.b64encode(img.getvalue()).decode()

    return render_template('index.html', plot_url=plot_url)

if __name__ == '__main__':
    app.run(debug=True)
2. 创建前端页面

/templates/index.html 中,展示分析图表。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>美团外卖数据分析</title>
</head>
<body>
    <h1>美团外卖餐品价格分布分析</h1>
    <img src="data:image/png;base64,{
             { plot_url }}" alt="Price Distribution">
</body>
</html>

六、总结

通过本文的实践,我们展示了如何使用 FlaskPython 构建一个爬取美团外卖点餐数据的分析系统。通过爬虫,我们获取了美团外卖的餐品数据,并使用 Pandas 进行清洗和处理。最后,通过 Matplotlib 展示了餐品价格和评分的分布图。

这种分析可以帮助我们更好地理解消费者偏好、热门商品,以及价格和评分的关系。你可以根据需求扩展系统,增加更多功能,如:

用户评分分析
餐品推荐系统
销量与订单趋势分析

未来,如果希望系统更强大,可以引入 数据库进行数据持久化,进一步提高系统的扩展性和性能。

希望本文能够帮助你在数据分析和 Web 开发的道路上走得更远!

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容