一、开发环境初始化
在开始构建档案培训公司数据分析系统之前,必须先准备好Python运行环境。本指南基于Python 3.8及以上版本编写,请确保已正确安装。打开终端或命令提示符,依次执行以下命令安装核心依赖库:
pip install requests beautifulsoup4 pandas openpyxl lxml
这些库的作用分别是:requests用于发送网络请求,beautifulsoup4用于解析HTML页面,pandas用于数据处理与排序,openpyxl用于生成Excel报表,lxml作为解析器提升解析速度。
二、项目结构搭建
为了保持代码的整洁与可维护性,请在本地创建一个名为archive_training_analysis的文件夹,并在其中创建以下三个Python文件:
- spider.py:负责网络请求与HTML解析。
- processor.py:负责数据清洗、排序与评分计算。
- main.py:程序的主入口,串联各个模块。
三、数据采集模块编写
打开spider.py,我们需要编写一个健壮的爬虫函数。这里的目标是模拟浏览器访问,获取包含“档案培训公司”信息的网页源码。为了防止被反爬虫机制拦截,必须设置完整的User-Agent头。
在spider.py中输入以下完整代码:
```python
import requests
from bs4 import BeautifulSoup
import random
import time
模拟浏览器的User-Agent列表
USER_AGENTS = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0'
]
def get_html(url):
"""
获取目标URL的HTML内容
:param url: 目标网址
:return: HTML文本或None
"""
headers = {
'User-Agent': random.choice(USER_AGENTS),
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8'
}
try:
设置超时时间为10秒
response = requests.get(url, headers=headers, timeout=10)
检查HTTP状态码
if response.status_code == 200:
显式设置编码,防止中文乱码
response.encoding = response.apparent_encoding
return response.text
else:
print(f"请求失败,状态码: {response.status_code}")
return None
except requests.RequestException as e:
print(f"请求异常: {e}")
return None
def parse_company_data(html):
"""
解析HTML,提取档案培训公司信息
注意:此处CSS选择器需根据实际抓取的网页结构进行修改
"""
if not html:
return []
soup = BeautifulSoup(html, 'lxml')
company_list = []
假设每个公司信息在一个class为'company-item'的div中
实际操作时请按F12打开开发者工具查看具体结构
items = soup.select('.company-item')
for item in items:
try:
name_tag = item.select_one('.company-name')
score_tag = item.select_one('.company-score')
desc_tag = item.select_one('.company-desc')
数据提取与去空
name = name_tag.get_text(strip=True) if name_tag else "未知公司"
score = float(score_tag.get_text(strip=True)) if score_tag else 0.0
desc = desc_tag.get_text(strip=True) if desc_tag else "暂无简介"
company_list.append({
'name': name,
'score': score,
'description': desc
})
except Exception as e:
print(f"解析单条数据出错: {e}")
continue
return company_list
测试代码(实际使用时由main.py调用)
if __name__ == '__main__':
这里使用一个示例URL,实际请替换为真实的档案培训公司列表页
target_url = "https://example.com/archive-training-companies"
html_content = get_html(target_url)
if html_content:
data = parse_company_data(html_content)
print(f"成功采集到 {len(data)} 条数据")
```
四、数据分析与清洗模块
数据采集完成后,往往包含重复数据或格式不统一的内容。打开processor.py,我们将使用Pandas库对数据进行清洗,并根据评分筛选出“前十名”。这是核心分析逻辑。
在processor.py中输入以下代码:
```python
import pandas as pd
def analyze_and_rank(data_list):
"""
对采集到的原始数据进行清洗、排序和筛选
:param data_list: 爬虫返回的字典列表
:return: 处理后的DataFrame对象
"""
if not data_list:
print("警告:传入的数据为空")
return pd.DataFrame()
1. 创建DataFrame
df = pd.DataFrame(data_list)
2. 数据去重:根据公司名称去重,保留第一条
df.drop_duplicates(subset=['name'], keep='first', inplace=True)
3. 数据清洗:去除描述中的空白字符
df['description'] = df['description'].str.strip()
4. 异常值处理:确保评分在0-10之间(假设满分10分)
df['score'] = df['score'].apply(lambda x: x if 0 <= x <= 10 else 0)
5. 核心逻辑:按评分降序排列
df_sorted = df.sort_values(by='score', ascending=False)
6. 筛选前十名
top_10 = df_sorted.head(10)
重置索引
top_10.reset_index(drop=True, inplace=True)
return top_10
def save_to_excel(df, filename='top_10_archive_companies.xlsx'):
"""
将分析结果保存为Excel文件
"""
if df.empty:
print("没有数据可保存")
return
try:
df.to_excel(filename, index=False, engine='openpyxl')
print(f"分析报告已生成:{filename}")
except Exception as e:
print(f"保存Excel失败: {e}")
```
五、主程序入口配置

我们需要将所有模块串联起来。打开main.py,编写程序的执行流程。为了确保读者能立即看到效果,我们在代码中内置了一段模拟数据生成逻辑。如果你有真实的URL,只需取消注释并替换即可。
在main.py中输入以下代码:
```python
from spider import get_html, parse_company_data
from processor import analyze_and_rank, save_to_excel
def main():
print(">>> 档案培训公司数据分析系统启动...")
配置目标URL
注意:实际运行时请将此处替换为真实的包含档案培训公司列表的网址
TARGET_URL = "https://www.example.com/training-list"
为了演示效果,这里默认使用模拟数据模式
如果要运行真实爬虫,将 USE_MOCK_DATA 设置为 False
USE_MOCK_DATA = True
raw_data = []
if USE_MOCK_DATA:
print(">>> 模式:使用模拟数据进行演示...")
raw_data = [
{'name': '兰台档案培训中心', 'score': 9.8, 'description': '专注于档案数字化与管理实务培训'},
{'name': '东方档案教育', 'score': 9.5, 'description': '提供档案管理员资格证考前辅导'},
{'name': '中档联培训', 'score': 9.2, 'description': '企业档案管理规范化解决方案提供商'},
{'name': '金档档案学院', 'score': 8.9, 'description': '档案信息化建设高端研修'},
{'name': '国信档案咨询', 'score': 8.7, 'description': '机关档案业务培训专家'},
{'name': '博雅文书培训', 'score': 8.5, 'description': '文秘与档案管理双技能培训'},
{'name': '神州档案网校', 'score': 8.3, 'description': '在线档案课程平台'},
{'name': '档案人俱乐部', 'score': 8.1, 'description': '档案从业者交流与提升'},
{'name': '易档科技培训', 'score': 7.9, 'description': '档案软件操作实战培训'},
{'name': '立信档案教育', 'score': 7.8, 'description': '档案法律法规解读'},
{'name': '优档培训', 'score': 7.5, 'description': '基础档案整理实操'},
{'name': '汉文档案', 'score': 7.2, 'description': '档案修复技术培训'},
]
else:
print(f">>> 模式:正在爬取真实数据 [{TARGET_URL}]...")
html = get_html(TARGET_URL)
if html:
raw_data = parse_company_data(html)
else:
print(">>> 错误:未能获取网页内容,程序终止。")
return
if not raw_data:
print(">>> 错误:未获取到任何原始数据。")
return
print(f">>> 数据采集完成,共获取 {len(raw_data)} 条记录。")
数据分析
print(">>> 正在进行数据分析与排名...")
result_df = analyze_and_rank(raw_data)
结果展示
if not result_df.empty:
print("\n>>> 【档案培训公司前十名】分析结果:")
print(result_df.to_string())
保存报告
save_to_excel(result_df)
else:
print(">>> 分析结果为空。")
if __name__ == '__main__':
main()
```
六、实操落地关键步骤
上述代码已经具备完整的逻辑,但要应用到真实的“档案培训公司前十名”采集场景中,你需要执行以下操作来适配目标网站:
1. 获取目标网址与CSS选择器
打开Chrome浏览器,访问你想要分析的档案培训公司列表页面(例如某行业排行榜网站)。按下F12键打开开发者工具。
点击左上角的“选择元素”图标(箭头),移动鼠标到页面上的公司名称处点击。在Elements面板中,右键点击高亮的代码行,选择Copy -> Copy selector。
将复制到的选择器(例如list > div.item > h3)填入spider.py中parse_company_data函数里的item.select_one('...')中。分别对名称、评分、描述执行此操作。
2. 运行程序
在main.py中将USE_MOCK_DATA修改为False,并将TARGET_URL修改为真实的网址。回到命令行,进入项目目录执行:
python main.py
3. 结果验证
程序运行结束后,当前目录下会生成top_10_archive_companies.xlsx文件。打开该文件,你将看到清洗后的、按评分从高到低排列的档案培训公司前十名名单,包含公司名、评分和简介。