前程无忧python工作薪资爬取及数据分析

本文介绍了一个Python脚本,用于从51Job网站爬取Python相关工作的详细信息,包括工作地点、薪资范围、公司名称及职位名称,并通过数据分析展示了Python职位的薪资分布情况。
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 15 15:31:51 2017

@author: Administrator
"""
'''
获取前程无忧python相关工作地点、薪水、公司、职位
'''

import requests
from bs4 import BeautifulSoup
headers={
        'UserAgent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'
        }
total=[]
for i in range(1,21):
    url='http://search.51job.com/list/070000%252C020000,000000,0000,00,9,99,Python,2,{}.html?lang=c&stype=1&postchannel=0000&workyear=99&cotype=99&degreefrom=99&jobterm=99&companysize=99&lonlat=0%2C0&radius=-1&ord_field=0&confirmdate=9&fromType=1&dibiaoid=0&address=&line=&specialarea=00&from=&welfare='.format(i)
    res=requests.get(url)
    res.encoding='gbk'
    #print(res.encoding)
    soup=BeautifulSoup(res.text,'html.parser')
    #print(soup)
    posts=soup.select('#resultList > div > p > span > a')
    #print(posts)
    post1=list(map(lambda x:x.text.strip(),posts))
    #print(post1)#获取职位名称
    comps=soup.select('#resultList > div > span.t2 > a')
    comp1=list(map(lambda x:x.text.strip(),comps))
    #print(comp1)#获取公司名称
    areas=soup.select('#resultList > div > span.t3')
    area1=list(map(lambda x:x.text.strip(),areas))
    #print(area1)#获取公司地点
    moneys=soup.select('#resultList > div > span.t4')
    money1=list(map(lambda x:x.text.strip(),moneys))
    #print(money1)#获取薪水    
    for post,comp,area,money in zip(post1,comp1,area1,money1):
        total.append({'post':post,'comp':comp,'area':area,'money':money})#打包成字典
print(total)

import pandas
deal=pandas.DataFrame(total)
#print(deal)

deal.to_excel('qianchengwuyou.xls')

#链接mongodb数据库
import pymongo
client = pymongo.MongoClient('localhost',27017) #'192.168.0.65',27777
db = client.cast
test = db.qianchengwuyou
'''
for i in total:
    test.save(i)#存储数据
'''
'''
query={'area':'上海'}
lt=test.count(query)
pos=list(test.find(query))
#print(pos)
import pandas
pos1=pandas.DataFrame(pos)
print(pos1)#提取数据
'''
'''
#以下从excel中提取数据,进行分析
import pandas as pd
a=pd.read_excel('qianchengwuyou.xls')
#筛选出有万和月的
b=[]
aa=a['money'].dropna()
for i in aa:    
    if '' in i and type(i)==str:
        if '' in i:
            b.append(i)
#print(b)

import re
#字符串分割
d=[]
for c in b:
    d.append(re.split('[-/]',c))
#print(d)
#最小值组成列表
min=[]
for e in d:
    min.append(e[0])
#print(min)
#最小值以千为单位
gg=[]
for ff in min:
    if len(ff)==1:
        ff=ff+'0'
    else:
        ff=ff.replace('.','')
        gg.append(ff)
#print(gg)
#min求和
kk=0
for hh in gg:
    kk=kk+int(hh)
print(kk)
#所有min平均值
ever=kk/len(gg)
print(ever)

#最大值组成列表
max=list(map(lambda x:x[1].strip('万'),d))
#print(max)
#最大值以千为单位
g=[]
for f in max:
    if len(f)==1:
        f=f+'0'
    else:
        f=f.replace('.','')
        g.append(f)
#print(g)
#max求和
k=0
for h in g:
    k=k+int(h)
print(k)
#所有max平均值
eve=k/len(g)
print(eve) 


import pandas
ik=list(map(int ,g))  
ik1=pandas.Series(ik)



import matplotlib.pyplot as plt
#概率分布直方图  
#高斯分布  
#均值为0
"""  
mean = 100 
#标准差为1,反应数据集中还是分散的值  
sigma = 1  
x=mean+sigma*np.random.randn(10000) 
""" 
plt.rcParams['font.sans-serif']=['SimHei']
fig,(ax0,ax1) = plt.subplots(nrows=2,figsize=(9,6))  
#第二个参数是柱子宽一些还是窄一些,越大越窄越密  
ax0.hist(ik,20,normed=1,histtype='bar',facecolor='yellowgreen',alpha=0.75)  
##pdf概率分布图,一万个数落在某个区间内的数有多少个  
ax0.set_title('基于前程无忧数据的python开发薪水调查')  
ax1.hist(ik1,normed=100,histtype='bar',facecolor='pink',alpha=0.75,cumulative=True,rwidth=0.8)  
#cdf累计概率函数,cumulative累计。比如需要统计小于5的数的概率  
ax1.set_title("cdf")  
fig.subplots_adjust(hspace=0.4)  
plt.show()


由柱状图可以看出python薪水在1.5万/月占比最高,接近30%,其次是薪水在2.5万/月,占比11%左右。

### 数据爬取前程无忧的实现方法 在使用 Python 进行数据爬取时,前程无忧是一个常见的目标网站,可以通过多种方式实现对招聘数据的抓取。常见的方法包括使用 `requests` 和 `BeautifulSoup` 进行基础爬虫开发,也可以使用功能更强大的框架如 `Scrapy`。此外,还可以结合正则表达式、`lxml` 和 `xpath` 进行数据解析,并将数据保存到 MySQL 或 Excel 文件中。 #### 爬虫技术实现 在爬虫实现中,首先需要获取网页的 HTML 内容,可以通过 `requests` 库完成请求。接着,可以使用 `BeautifulSoup` 解析 HTML,提取所需数据,例如职位名称、公司名称、薪资范围等信息。例如: ```python import requests from bs4 import BeautifulSoup def get_one_page(url): response = requests.get(url) if response.status_code == 200: return response.text return None def parse_one_page(html): soup = BeautifulSoup(html, 'lxml') # 提取职位信息 jobs = soup.select('.dw_table .el') for job in jobs: yield { '职位': job.select_one('.t1 a')['title'], '公司': job.select_one('.t2 a')['title'], '地址': job.select_one('.t3').get_text(), '薪资': job.select_one('.t4').get_text(), '日期': job.select_one('.t5').get_text() } ``` #### 数据存储 爬取数据后,可以选择将数据存储到数据库或文件中。例如,使用 `pymysql` 将数据存储到 MySQL 中: ```python import pymysql def write_to_mysql(data): connection = pymysql.connect(host='localhost', user='root', password='password', db='job_data') cursor = connection.cursor() sql = 'INSERT INTO jobs (职位, 公司, 地址, 薪资, 日期) VALUES (%s, %s, %s, %s, %s)' try: cursor.execute(sql, (data['职位'], data['公司'], data['地址'], data['薪资'], data['日期'])) connection.commit() except Exception as e: print(e) connection.rollback() finally: connection.close() ``` 如果选择将数据保存为 CSV 文件,可以使用 `pandas` 库: ```python import pandas as pd def save_to_csv(data): df = pd.DataFrame(data) df.to_csv('job_info.csv', mode='a+', index=False, header=True) ``` #### 爬虫性能优化 为了提高爬虫性能,可以采用异步爬虫技术,例如使用 `aiohttp` 和 `asyncio` 实现并发请求。这样可以在短时间内抓取大量数据。此外,还可以使用 `Scrapy` 框架,它提供了更强大的功能,如自动分页、中间件、管道等,适合大规模爬虫项目。 #### 数据分析与可视化 爬取数据后,可以使用 `matplotlib` 或 `seaborn` 进行数据分析和可视化。例如,可以绘制薪资分布图、岗位数量分布图等: ```python import matplotlib.pyplot as plt import pandas as pd df = pd.read_csv('job_info.csv') salary_counts = df['薪资'].value_counts() salary_counts.plot(kind='bar') plt.title('薪资分布') plt.xlabel('薪资') plt.ylabel('数量') plt.show() ``` #### 注意事项 - **反爬虫机制**:前程无忧可能会有反爬虫机制,如 IP 封锁、验证码等。可以通过设置请求头、使用代理 IP、设置请求间隔等方式规避。 - **合法性**:在进行数据爬取时,应遵守网站的 `robots.txt` 协议,确保合法合规。 - **代码维护**:由于网站结构可能会发生变化,爬虫代码需要定期维护,确保长期运行的稳定性。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值