API文档
本文档详细介绍美团店铺数据处理工具的核心API接口和使用方法。
📚 核心API概览
主要模块
模块 | 文件 | 主要类 | 功能 |
---|---|---|---|
数据处理 | malatang_processor.py | MalatangProcessor | 核心数据处理逻辑 |
数据提取 | malatang_processor.py | DataExtractor | JSON数据解析和提取 |
Excel管理 | malatang_processor.py | ExcelManager | Excel文件操作 |
图片下载 | malatang_processor.py | ImageDownloader | 图片下载和处理 |
GUI处理器 | gui_processor.py | GUIProcessor | GUI专用处理器 |
界面组件 | gui_fluent.py | MalatangFluentGUI | 主界面类 |
🔧 核心处理器API
MalatangProcessor
主要的数据处理类,提供完整的数据处理功能。
类定义
python
class MalatangProcessor:
"""主处理类"""
def __init__(self):
self.logger = Logger.setup_logger()
self.data_extractor = DataExtractor(self.logger)
self.excel_manager = ExcelManager(self.logger)
self.image_downloader = ImageDownloader(self.logger)
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
主要方法
process_file()
处理数据文件的主要入口方法。
python
def process_file(self) -> None:
"""
处理文件
功能:
- 解析JSON数据文件
- 提取商品信息
- 保存到Excel
- 下载图片
异常:
- FileNotFoundError: 输入文件不存在
- JSONDecodeError: JSON格式错误
- PermissionError: 文件权限不足
"""
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
使用示例:
python
# 创建处理器实例
processor = MalatangProcessor()
# 执行处理
try:
processor.process_file()
print("处理完成!")
except Exception as e:
print(f"处理失败: {e}")
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
📊 数据提取API
DataExtractor
负责JSON数据解析和商品信息提取。
类定义
python
class DataExtractor:
"""数据提取器"""
def __init__(self, logger):
self.logger = logger
1
2
3
4
5
2
3
4
5
主要方法
parse_json_file(file_path)
解析JSON文件。
python
def parse_json_file(self, file_path: str) -> Dict:
"""
解析JSON文件
参数:
file_path (str): JSON文件路径
返回:
Dict: 解析后的数据字典
异常:
FileNotFoundError: 文件不存在
JSONDecodeError: JSON格式错误
UnicodeDecodeError: 文件编码错误
"""
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
使用示例:
python
extractor = DataExtractor(logger)
# 解析JSON文件
try:
data = extractor.parse_json_file("malatang.txt")
print(f"解析成功,数据类型: {type(data)}")
except FileNotFoundError:
print("文件不存在")
except json.JSONDecodeError as e:
print(f"JSON格式错误: {e}")
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
extract_products(data)
从解析的数据中提取商品信息。
python
def extract_products(self, data: Dict) -> List[Dict]:
"""
提取商品信息
参数:
data (Dict): 解析后的JSON数据
返回:
List[Dict]: 商品信息列表
数据结构:
[
{
'name': str, # 商品名称
'price': float, # 原价(元)
'discount_price': float, # 折扣价(元)
'month_sale': int, # 月销量
'image_url': str, # 图片链接
'image_filename': str # 图片文件名
}
]
"""
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
使用示例:
python
# 提取商品信息
products = extractor.extract_products(data)
print(f"提取到 {len(products)} 个商品")
# 遍历商品信息
for product in products:
print(f"商品: {product['name']}, 价格: {product['price']}")
1
2
3
4
5
6
7
2
3
4
5
6
7
_extract_single_product(item)
提取单个商品信息(内部方法)。
python
def _extract_single_product(self, item: Dict) -> Optional[Dict]:
"""
提取单个商品信息
参数:
item (Dict): 单个商品的原始数据
返回:
Optional[Dict]: 提取的商品信息,失败时返回None
"""
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
📋 Excel管理API
ExcelManager
负责Excel文件的读写和数据管理。
类定义
python
class ExcelManager:
"""Excel管理器"""
def __init__(self, logger):
self.logger = logger
1
2
3
4
5
2
3
4
5
主要方法
load_existing_data(file_path)
加载现有的Excel数据。
python
def load_existing_data(self, file_path: str) -> pd.DataFrame:
"""
加载现有Excel数据
参数:
file_path (str): Excel文件路径
返回:
pd.DataFrame: 现有数据的DataFrame
注意:
如果文件不存在,返回空的DataFrame
"""
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
使用示例:
python
excel_manager = ExcelManager(logger)
# 加载现有数据
existing_df = excel_manager.load_existing_data("malatang_products.xlsx")
print(f"现有数据行数: {len(existing_df)}")
# 检查是否有数据
if not existing_df.empty:
print("现有商品列表:")
print(existing_df['商品名称'].tolist())
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
save_products_to_excel(products, file_path)
保存商品数据到Excel文件。
python
def save_products_to_excel(self, products: List[Dict], file_path: str) -> None:
"""
保存商品数据到Excel
参数:
products (List[Dict]): 商品信息列表
file_path (str): Excel文件保存路径
功能:
- 自动去重(基于商品名称)
- 追加新数据到现有文件
- 添加时间戳
异常:
PermissionError: 文件被占用或权限不足
OSError: 磁盘空间不足
"""
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
使用示例:
python
# 准备商品数据
products = [
{
'name': '麻辣鸡锁骨',
'price': 12.0,
'discount_price': 10.0,
'month_sale': 156,
'image_url': 'https://example.com/image.jpg',
'image_filename': '麻辣鸡锁骨.jpg'
}
]
# 保存到Excel
try:
excel_manager.save_products_to_excel(products, "output.xlsx")
print("保存成功!")
except PermissionError:
print("文件被占用,请关闭Excel后重试")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
🖼️ 图片下载API
ImageDownloader
负责图片下载和格式转换。
类定义
python
class ImageDownloader:
"""图片下载器"""
def __init__(self, logger):
self.logger = logger
self.session = requests.Session()
1
2
3
4
5
6
2
3
4
5
6
主要方法
download_images(products, images_dir)
批量下载商品图片。
python
def download_images(self, products: List[Dict], images_dir: str) -> int:
"""
批量下载图片
参数:
products (List[Dict]): 商品信息列表
images_dir (str): 图片保存目录
返回:
int: 成功下载的图片数量
功能:
- 自动创建目录
- 跳过已存在的图片
- 自动重试失败的下载
- 格式转换(WebP -> JPG)
"""
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
使用示例:
python
downloader = ImageDownloader(logger)
# 下载图片
downloaded_count = downloader.download_images(products, "images/")
print(f"成功下载 {downloaded_count} 张图片")
1
2
3
4
5
2
3
4
5
_download_single_image(url, file_path)
下载单个图片(内部方法)。
python
def _download_single_image(self, url: str, file_path: str) -> bool:
"""
下载单个图片
参数:
url (str): 图片URL
file_path (str): 保存路径
返回:
bool: 下载是否成功
配置:
- 超时时间: 30秒
- 重试次数: 3次
- User-Agent: 模拟浏览器
"""
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
_convert_to_jpg(image_path)
转换图片格式为JPG。
python
def _convert_to_jpg(self, image_path: str) -> bool:
"""
转换图片格式为JPG
参数:
image_path (str): 图片文件路径
返回:
bool: 转换是否成功
功能:
- 支持WebP, PNG, BMP等格式
- 透明背景替换为白色
- 高质量压缩(95%)
- 自动删除原文件
"""
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
🖥️ GUI处理器API
GUIProcessor
专门为GUI界面设计的处理器,提供回调和进度反馈。
类定义
python
class GUIProcessor:
"""GUI专用处理器"""
def __init__(self, log_callback=None, progress_callback=None):
self.log_callback = log_callback
self.progress_callback = progress_callback
self.logger = logging.getLogger(__name__)
1
2
3
4
5
6
7
2
3
4
5
6
7
主要方法
process_file(input_file, output_excel, images_dir)
处理文件(GUI版本)。
python
def process_file(self, input_file: str, output_excel: str, images_dir: str) -> Dict:
"""
处理文件(GUI版本)
参数:
input_file (str): 输入JSON文件路径
output_excel (str): 输出Excel文件路径
images_dir (str): 图片保存目录
返回:
Dict: 处理结果统计
{
'total_products': int, # 总商品数
'new_products': int, # 新增商品数
'downloaded_images': int, # 下载图片数
'skipped_images': int, # 跳过图片数
'failed_images': int, # 失败图片数
'excel_file': str, # Excel文件路径
'images_dir': str # 图片目录路径
}
回调:
- log_callback(message, level): 日志回调
- progress_callback(percentage): 进度回调
"""
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
使用示例:
python
def log_handler(message, level):
print(f"[{level}] {message}")
def progress_handler(percentage):
print(f"进度: {percentage}%")
# 创建GUI处理器
gui_processor = GUIProcessor(
log_callback=log_handler,
progress_callback=progress_handler
)
# 执行处理
results = gui_processor.process_file(
input_file="malatang.txt",
output_excel="output.xlsx",
images_dir="images/"
)
print(f"处理完成: {results}")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
🎨 界面API
MalatangFluentGUI
主界面类,基于QFluentWidgets实现。
类定义
python
class MalatangFluentGUI(FluentWindow):
"""美团店铺数据处理工具 - Fluent Design主界面"""
def __init__(self):
super().__init__()
self.setWindowTitle("美团店铺数据处理工具")
self.setFixedSize(1400, 1244)
1
2
3
4
5
6
7
2
3
4
5
6
7
主要方法
start_processing()
开始处理数据。
python
def start_processing(self):
"""
开始处理数据
功能:
- 验证输入文件
- 启动后台处理线程
- 自动启用文件监控
- 更新界面状态
"""
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
add_log(message, level)
添加日志信息。
python
def add_log(self, message: str, level: str = "INFO"):
"""
添加日志信息
参数:
message (str): 日志消息
level (str): 日志级别 (INFO, WARNING, ERROR, SUCCESS)
功能:
- 彩色日志显示
- 自动滚动到最新
- 时间戳添加
"""
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
🔧 配置API
Config类
配置管理类,提供所有可配置参数。
python
class Config:
"""配置类"""
# 文件路径配置
INPUT_FILE = "malatang.txt"
OUTPUT_EXCEL = "malatang_products.xlsx"
IMAGES_DIR = "images"
LOG_FILE = "malatang_processor.log"
# 网络配置
REQUEST_TIMEOUT = 30
MAX_RETRIES = 3
# 图片转换配置
CONVERT_TO_JPG = True
JPG_QUALITY = 95
JPG_BACKGROUND_COLOR = (255, 255, 255)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
使用示例:
python
# 修改配置
Config.REQUEST_TIMEOUT = 60 # 增加超时时间
Config.MAX_RETRIES = 5 # 增加重试次数
# 使用配置
processor = MalatangProcessor()
# 处理器会自动使用更新后的配置
1
2
3
4
5
6
7
2
3
4
5
6
7
📝 使用示例
完整处理流程
python
import logging
from malatang_processor import MalatangProcessor, Config
# 配置日志
logging.basicConfig(level=logging.INFO)
# 自定义配置
Config.IMAGES_DIR = "my_images"
Config.OUTPUT_EXCEL = "my_products.xlsx"
# 创建处理器
processor = MalatangProcessor()
try:
# 执行处理
processor.process_file()
print("✅ 处理完成!")
except FileNotFoundError:
print("❌ 输入文件不存在")
except Exception as e:
print(f"❌ 处理失败: {e}")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
GUI集成示例
python
from PyQt5.QtWidgets import QApplication
from gui_fluent import MalatangFluentGUI
# 创建应用
app = QApplication([])
# 创建主界面
window = MalatangFluentGUI()
window.show()
# 运行应用
app.exec_()
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
API使用建议
- 优先使用高级API(如MalatangProcessor)
- 需要自定义功能时使用组件API
- GUI应用建议使用GUIProcessor
- 记得处理异常和错误情况
注意事项
- 所有文件路径建议使用绝对路径
- 网络操作需要考虑超时和重试
- 大量数据处理时注意内存使用
- GUI操作必须在主线程中进行