1. 程式人生 > >爬取拉鉤崗位資訊生成圖表和詞雲

爬取拉鉤崗位資訊生成圖表和詞雲

1.環境準備

py版本:python3.6.7

需要使用的包列表檔案: requirements.txt

certifi==2018.10.15
chardet==3.0.4
cycler==0.10.0
idna==2.7
jieba==0.39
kiwisolver==1.0.1
matplotlib==3.0.1
numpy==1.15.4
pandas==0.23.4
Pillow==5.3.0
pyparsing==2.3.0
python-dateutil==2.7.5
pytz==2018.7
requests==2.20.1
scipy==1.1.0
six==1.11.0
urllib3
==1.24.1 wordcloud==1.5.0

製作詞雲的圖片一張:cloud.jpg

建立一個目錄:JobPostion 用來存放爬取的csv檔案格式的資料

用來解決詞雲中的亂碼的字型檔案   Arial Unicode MS.ttf

2.爬取拉勾資料程式碼 

#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time    : 2018/11/16/016 21:44
# @Author  : BenjaminYang
# @FileName: lagou.py
# @Software: PyCharm
# @Blog :http://cnblogs.com/benjamin77 import requests import math import time import pandas as pd def get_json(url, num): '''從網頁獲取JSON,使用POST請求,加上頭部資訊''' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36
', 'Host': 'www.lagou.com', 'Referer':'https://www.lagou.com/jobs/list_python%E5%BC%80%E5%8F%91?labelWords=&;fromSearch=true&suginput=', 'X-Anit-Forge-Code': '0', 'X-Anit-Forge-Token': 'None', 'X-Requested-With': 'XMLHttpRequest' } data = { 'first': 'true', 'pn': num, 'kd': '運維工程師'} res = requests.post(url, headers=headers, data=data) res.raise_for_status() res.encoding = 'utf-8' # 得到包含職位資訊的字典 page = res.json() return page def get_page_num(count): '''通過崗位總數與除以每頁顯示數15,如果超過17頁就顯示17頁,不超過就顯示計算的頁數''' res=math.ceil(count/15) if res >17: return 17 else: return res def get_page_info(jobs_list): page_info_list = [] for i in jobs_list: job_info = [] job_info.append(i['companyFullName']) # 公司全名 job_info.append(i['companyShortName']) # 公司簡稱 job_info.append(i['companySize']) # 公司規模 job_info.append(i['financeStage']) # 融資階段 job_info.append(i['district']) # 區域 job_info.append(i['positionName']) # 職位名稱 job_info.append(i['workYear']) # 工作經驗 job_info.append(i['education']) # 學歷要求 job_info.append(i['salary']) # 工資 job_info.append(i['positionAdvantage']) # 職位福利 page_info_list.append(job_info) return page_info_list if __name__=='__main__': url='https://www.lagou.com/jobs/positionAjax.json?city=%E6%9D%AD%E5%B7%9E&needAddtionalResult=false' page_one=get_json(url,1)#獲取一頁的json資料 total_count=page_one['content']['positionResult']['totalCount']#崗位總數 num=get_page_num(total_count)#當前總頁數 print('職位總數:{},當前總頁數:{}'.format(total_count,num)) time.sleep(20) print(page_one) total_info=[] for n in range(1,num+1):#獲取每一頁的json資料 page =get_json(url,n) jobs_list=page_one['content']['positionResult']['result'] page_info=get_page_info(jobs_list) total_info+=page_info time.sleep(30) df=pd.DataFrame(data=total_info,columns=['公司全名','公司簡稱','公司規模','融資階段','區域','職位名稱','工作經驗','學歷要求','工資','職位福利']) df.to_csv('./JobPosition/運維工程師.csv',index=False) print('已儲存csv檔案')

執行完會在 JobPostion目錄下生成一個 csv檔案

3.繪圖程式碼

#!/usr/bin/python
# -*- coding: utf-8 -*-
# @Time    : 2018/11/17/017 13:39
# @Author  : BenjaminYang
# @FileName: data_analysis.py
# @Software: PyCharm
# @Blog    :http://cnblogs.com/benjamin77

import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from wordcloud import WordCloud
from scipy.misc import imread
import jieba
from pylab import mpl


#設定字型樣式
mpl.rcParams['font.family']='sans-serif'
mpl.rcParams['font.sans-serif']='simhei'

# 1.計算薪資,生成直方圖,25%
def get_salary_chart(df):
    df['salary']=df['工資'].str.findall('\d+')
    avg_salary=[]
    for k in df['salary']:
        int_list=[int(n) for n in k]
        # 10k-16k  正常要工資是 10+16/4=14
        avg_wage=int_list[0]+(int_list[1]-int_list[0])/4
        avg_salary.append(avg_wage)
    df['月工資']=avg_salary
    df.to_csv('draft.csv',index=False)

    print('崗位工資比例: \n{}'.format(df['月工資'].describe()))



    plt.xticks(fontsize=12)
    plt.yticks( fontsize=12)
    plt.xlabel('工資(K)', fontsize=14)
    plt.ylabel('次數', fontsize=14)
    plt.hist(df['月工資'],bins=12)
    plt.title(filename+'薪資直方圖', fontsize=14)
    plt.savefig('histogram.jpg')
    plt.show()

    #餅圖
def get_region_chart():
    count=df['區域'].value_counts()
    print(count)
    plt.pie(count,labels=count.keys(),labeldistance=1.4,autopct='%2.1f%%')
    plt.axis('equal')
    plt.title(filename+'崗位區域分佈圖', fontsize=14 )
    plt.legend(loc='upper left',bbox_to_anchor=(-0.1,1))
    plt.savefig('pie_chart.jpg')
    plt.show()

def get_cloud_chart():
    text = ''
    for line in df['職位福利']:
        text += line

    # 5.1 使用jieba模組將字串分割為單詞列表
    cut_text = ' '.join(jieba.cut(text))  # 字串分詞
    cloud = WordCloud(
        font_path='Arial Unicode MS.ttf',
        background_color='white',  # 背景設定成(white)白色
        mask=imread('./cloud.jpg'),  # 設定背景圖
        max_words=1000,
        max_font_size=100
    )

    word_cloud = cloud.generate(cut_text)
    # 5.2 儲存詞雲圖片
    word_cloud.to_file('word_cloud.jpg')
    plt.imshow(word_cloud)
    plt.axis('off')
    plt.show()

if __name__ == '__main__':
    filename='運維工程師'
    f=open('./JobPosition/'+filename+'.csv',encoding='utf-8')
    df=pd.read_csv(f)
    #get_salary_chart(df)
    #get_region_chart()
    get_cloud_chart()

4.效果展示

 4.1draft.csv

4.2直方圖

4.3餅圖

4.4詞雲圖

5.填坑記

 在生成詞雲的時候,由於沒有將字型檔案  Arial Unicode MS.ttf 放在當前工作目錄中,導致生成詞雲圖片一致失敗且亂碼。

OSError: cannot open resource

解決方法: 將ttf字型檔案放在當前工作目錄即可

 

matplotlib 畫圖亂碼

UserWarning:
findfont: Font family ['sans-serif'] not found.
Falling back to DejaVu Sans
(prop.get_family(), self.defaultFamily[fontext]))

 

解決方法,複製一個windows字型目錄下的 Arial Unicode MS.ttf 檔案到matlib的包目錄的ttf目錄下

圈起來的部分根據自己環境更改。

 

通過命令找到 matplotlib的配置目錄

 將這個json檔案刪除,他是一個字型的快取檔案,然後重新run指令碼就會生成新的快取檔案。將剛剛複製過去的字型載入到快取檔案裡。

不刪除快取檔案重新生成的話,就會提示上面的報錯 找不到那個字型。