# 如何讓Python爬取招聘網站數據并做數據可視化處理
## 目錄
1. [引言](#引言)
2. [技術棧概述](#技術棧概述)
3. [環境準備](#環境準備)
4. [爬蟲開發實戰](#爬蟲開發實戰)
- [4.1 目標網站分析](#41-目標網站分析)
- [4.2 基礎爬蟲實現](#42-基礎爬蟲實現)
- [4.3 反爬應對策略](#43-反爬應對策略)
5. [數據清洗與存儲](#數據清洗與存儲)
6. [數據可視化實現](#數據可視化實現)
- [6.1 薪資分布分析](#61-薪資分布分析)
- [6.2 崗位需求熱力圖](#62-崗位需求熱力圖)
- [6.3 技能詞云圖](#63-技能詞云圖)
7. [完整代碼示例](#完整代碼示例)
8. [總結與擴展](#總結與擴展)
## 引言
在當今大數據時代,招聘市場數據分析已成為企業和求職者的重要參考依據。本文將詳細介紹如何使用Python技術棧構建完整的招聘數據采集與分析系統,涵蓋從網頁爬取到可視化呈現的全流程。
## 技術棧概述
- **爬蟲框架**:Requests + BeautifulSoup(簡易場景) / Scrapy(工程化項目)
- **數據存儲**:CSV/Excel(輕量級)、MySQL/MongoDB(大規模)
- **數據分析**:Pandas + NumPy
- **可視化庫**:Matplotlib + Seaborn(基礎圖表)、PyEcharts(交互式)、WordCloud(詞云)
- **反爬方案**:User-Agent輪換、IP代理、Selenium模擬
## 環境準備
```python
# 創建虛擬環境(推薦)
python -m venv job_venv
source job_venv/bin/activate # Linux/Mac
job_venv\Scripts\activate # Windows
# 安裝依賴庫
pip install requests beautifulsoup4 pandas matplotlib seaborn pyecharts wordcloud jieba
以智聯招聘為例(注:實際項目請遵守robots.txt協議):
https://sou.zhaopin.com/?jl=城市代碼&kw=關鍵詞
import requests
from bs4 import BeautifulSoup
import pandas as pd
def fetch_jobs(keyword, city_code='530', pages=3):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36...'
}
base_url = f"https://sou.zhaopin.com/?jl={city_code}&kw={keyword}"
job_list = []
for page in range(1, pages+1):
params = {'p': page}
try:
response = requests.get(base_url, headers=headers, params=params)
soup = BeautifulSoup(response.text, 'html.parser')
for item in soup.select('.joblist-box__item'):
job = {
'title': item.select_one('.job-name').text.strip(),
'company': item.select_one('.company-name').text.strip(),
'salary': item.select_one('.salary').text.strip(),
'location': item.select_one('.job-area').text.strip(),
'experience': item.select_one('.job-demand span:nth-child(2)').text,
'education': item.select_one('.job-demand span:nth-child(3)').text
}
job_list.append(job)
except Exception as e:
print(f"第{page}頁抓取失敗: {str(e)}")
return pd.DataFrame(job_list)
headers = {
'User-Agent': random.choice(user_agent_list),
'Referer': 'https://www.zhaopin.com/',
'Accept-Language': 'zh-CN,zh;q=0.9'
}
proxies = {
'http': 'http://12.34.56.78:8888',
'https': 'https://12.34.56.78:8888'
}
response = requests.get(url, proxies=proxies)
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument('--headless')
driver = webdriver.Chrome(options=options)
driver.get(url)
soup = BeautifulSoup(driver.page_source, 'html.parser')
def clean_data(df):
# 薪資標準化(示例:15-20萬/年 → 17.5)
df['salary_avg'] = df['salary'].apply(lambda x:
sum([float(i) for i in re.findall(r'(\d+\.?\d*)', x)])/2
if '-' in x else float(re.search(r'(\d+\.?\d*)', x).group()))
# 學歷要求標準化
edu_map = {'大專': '???#39;, '本科': '學士', '碩士': '碩士'}
df['education'] = df['education'].replace(edu_map)
# 保存到CSV
df.to_csv('job_data.csv', index=False, encoding='utf_8_sig')
return df
import matplotlib.pyplot as plt
import seaborn as sns
plt.figure(figsize=(10,6))
sns.boxplot(x='education', y='salary_avg', data=df)
plt.title('不同學歷薪資分布對比')
plt.xlabel('學歷要求')
plt.ylabel('平均薪資(萬/年)')
plt.savefig('salary_distribution.png')
from pyecharts import options as opts
from pyecharts.charts import Geo
geo = (
Geo()
.add_schema(maptype="china")
.add("崗位分布",
[list(z) for z in zip(df['company'], df['location'])],
type_="heatmap")
.set_global_opts(
title_opts=opts.TitleOpts(title="全國崗位需求熱力圖"),
visualmap_opts=opts.VisualMapOpts(max_=100)
)
)
geo.render("geo_heatmap.html")
from wordcloud import WordCloud
import jieba
text = ' '.join(df['title'].tolist() + df['experience'].tolist())
wordlist = ' '.join(jieba.cut(text))
wc = WordCloud(
font_path='simhei.ttf',
background_color='white',
max_words=200
).generate(wordlist)
plt.imshow(wc)
plt.axis("off")
plt.savefig('wordcloud.png')
(因篇幅限制,此處展示核心結構,完整代碼需包含以下模塊)
# main.py
import crawling
import cleaning
import visualization
if __name__ == "__main__":
# 1. 數據采集
raw_df = crawling.fetch_jobs('Python', pages=5)
# 2. 數據清洗
clean_df = cleaning.clean_data(raw_df)
# 3. 可視化分析
visualization.plot_salary(clean_df)
visualization.generate_wordcloud(clean_df)
本文代碼已在GitHub開源:
https://github.com/example/job-spider-demo
數據采集時間:2023年8月 | 可視化工具版本:PyEcharts 2.0 “`
(注:實際文章應包含更多細節說明和代碼注釋,此處為保持3700字篇幅的簡化版結構。完整實現需根據目標網站結構調整解析邏輯,并添加更豐富的數據分析維度。)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。