import requests
import math
import pandas as pd
import time
def get_json(url,num):
'''''从网页获取JSON,使用POST请求,加上头部信息'''
my_headers = {
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language':'zh-CN,zh;q=0.9',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Content-Length': '55',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Cookie': '_ga=GA1.2.765752527.1538018402; user_trace_token=20180927112000-37beaeb4-c204-11e8-bb60-5254005c3644; LGUID=20180927112000-37beb2b2-c204-11e8-bb60-5254005c3644; index_location_city=%E5%85%A8%E5%9B%BD; JSESSIONID=ABAAABAABEEAAJAF72281935F8B1A25C8FD1DCE9FB23CEF; _gid=GA1.2.1024355859.1539227932; Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1538034530,1538034547,1538034560,1539227934; TG-TRACK-CODE=search_code; LGSID=20181011152610-ecdb69fd-cd26-11e8-afa8-525400f775ce; _gat=1; LGRID=20181011160410-3c4f1b3c-cd2c-11e8-afac-525400f775ce; Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1539245052; SEARCH_ID=0555f2889e5049b09a78dcc9fad252b0',
'Host': 'www.lagou.com',
'Origin': 'https://www.lagou.com',
'Referer': 'https://www.lagou.com/jobs/list_%E7%94%9F%E7%89%A9%E4%BF%A1%E6%81%AF?px=default&city=%E5%85%A8%E5%9B%BD',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
'X-Anit-Forge-Code': '0',
'X-Anit-Forge-Token': 'None',
'X-Requested-With':'XMLHttpRequest'
}
my_data = {
'first': 'true',
'pn':num,
'kd':'生物信息'
}
res = requests.post(url, headers = my_headers, data = my_data)
res.raise_for_status()
res.encoding = 'utf-8'
# 得到包含职位信息的字典
page = res.json()
return page
def get_page_num(count):
'''''计算要抓取的页数'''
# 每页15个职位,向上取整
res = math.ceil(count/15)
# 拉勾网最多显示30页结果
if res > 30:
return 30
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['city'])
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
url = 'https://www.lagou.com/jobs/positionAjax.json?px=default&needAddtionalResult=false'
# 先设定页数为1,获取总的职位数
page_1 = get_json(url,1)
total_count = page_1['content']['positionResult']['totalCount']
num = get_page_num(total_count)
total_info = []
time.sleep(20)
print('职位总数:{},页数:{}'.format(total_count,num))
职位总数:57267,页数:30
for n in range(1,num+1):
# 对每个网页读取JSON, 获取每页数据
page = get_json(url,n)
jobs_list = page['content']['positionResult']['result']
page_info = get_page_info(jobs_list)
total_info += page_info
print('已经抓取第{}页, 职位总数:{}'.format(n, len(total_info)))
# 每次抓取完成后,暂停一会,防止被服务器拉黑
time.sleep(30)
#将总数据转化为data frame再输出
df = pd.DataFrame(data = total_info,columns = ['公司全名','公司简称','公司规模','融资阶段','工作地点','区域','职位名称','工作经验','学历要求','工资','职位福利'])
#df.to_csv('lagou_jobs.csv',index = False)
#print('已保存为csv文件.')
已经抓取第1页, 职位总数:15
已经抓取第2页, 职位总数:30
已经抓取第3页, 职位总数:45
已经抓取第4页, 职位总数:60
已经抓取第5页, 职位总数:75
已经抓取第6页, 职位总数:90
已经抓取第7页, 职位总数:105
已经抓取第8页, 职位总数:120
已经抓取第9页, 职位总数:135
已经抓取第10页, 职位总数:150
已经抓取第11页, 职位总数:165
已经抓取第12页, 职位总数:180
已经抓取第13页, 职位总数:195
已经抓取第14页, 职位总数:210
已经抓取第15页, 职位总数:225
已经抓取第16页, 职位总数:240
已经抓取第17页, 职位总数:255
已经抓取第18页, 职位总数:270
已经抓取第19页, 职位总数:285
已经抓取第20页, 职位总数:300
已经抓取第21页, 职位总数:315
已经抓取第22页, 职位总数:330
已经抓取第23页, 职位总数:345
已经抓取第24页, 职位总数:360
已经抓取第25页, 职位总数:375
已经抓取第26页, 职位总数:390
已经抓取第27页, 职位总数:405
已经抓取第28页, 职位总数:420
已经抓取第29页, 职位总数:435
已经抓取第30页, 职位总数:450
df
df.to_excel("result.xls",index=False,encoding="utf_8")
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import jieba
from wordcloud import WordCloud # 词云
import matplotlib as mpl # 配置字体
from pyecharts import Geo # 地理图
plt.rcParams['font.sans-serif']=['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
plt.rcParams["axes.labelsize"] = 16.
plt.rcParams["xtick.labelsize"] = 14.
plt.rcParams["ytick.labelsize"] = 14.
plt.rcParams["legend.fontsize"] = 12.
plt.rcParams["figure.figsize"] = [15., 15.]
# 读入数据
df = pd.read_excel('result.xls')
# 查看头几行
df.head()
6.学历要求
很明显看到,目前来说本科需求量最大,博士就是稀有动物了
df['学历要求'].value_counts().plot(kind='barh',rot=0)
plt.show()
df['工作经验'].value_counts().plot(kind='barh') #绘制条形图
plt.show()
df['工作地点'].value_counts().plot(kind='pie',autopct='%1.2f%%',explode=np.linspace(0,1.5,37))
plt.show()
df['工资'].value_counts().plot(kind='barh') #绘制条形图
plt.show()
#从lambda一直到*1000,是一个匿名函数,*1000的原因是这里显示的是几K几K的,我们把K切割掉,只要数字,就*1000了
data2 = list(map(lambda x:(df['学历要求'][x],eval(re.split('k|K',df['工资'][x])[0])*1000),range(len(df))))
#再把data2框架起来
data3 = pd.DataFrame(data2)
sort_by_degree['sortby'] = sort_by_degree['degree'].map(degree_mappings)
sort_by_degree.sort_values(by='sortby', inplace=True)
sort_by_degree
degree | counts | sortby | |
---|---|---|---|
0 | 不限 | 39 | 1 |
2 | 大专 | 110 | 2 |
3 | 本科 | 256 | 3 |
4 | 硕士 | 43 | 4 |
1 | 博士 | 2 | 5 |
degree_mappings = {'不限':1, '大专':2, '本科':3, '硕士':4, '博士':5}
group_by_degree = data3.groupby([0])[1]
df_degree = []
for group in sort_by_degree['degree']:
v = group_by_degree.get_group(group).values
df_degree.append(v)
ax9 = plt.figure(figsize=(10, 8)).add_subplot(111)
sns.boxplot(data=df_degree)
ax9.set_xticklabels(sort_by_degree['degree'], fontsize=18)
ax9.set_title('不同学历的薪酬分布', fontsize=22)
ax9.set_ylabel('薪酬K/月', fontsize=20)
plt.show()