您好,欢迎来到抵帆知识网。
搜索
您的当前位置:首页Python爬虫入门:如何爬取招聘网站并进行分析

Python爬虫入门:如何爬取招聘网站并进行分析

来源:抵帆知识网
0 前言

工作之余,时常会想能做点什么有意思的玩意。互联网时代,到处都是互联网思维,大数据、深度学习、人工智能,这些新词刮起一股旋风。所以笔者也赶赶潮流,买了本Python爬虫书籍研读起来。

网络爬虫,顾名思义就是将互联网上的内容按照自己编订的规则抓取保存下来。理论上来讲,浏览器上只要眼睛能看到的网页内容都可以抓起保存下来,当然很多网站都有自己的反爬虫技术,不过反爬虫技术的存在只是增加网络爬虫的成本而已,所以爬取些有更有价值的内容,也就对得起技术得投入。

1案例选取

人有1/3的时间在工作,有一个开心的工作,那么1/3的时间都会很开心。所以我选取招聘网站来作为我第一个学习的案例。

前段时间和一个老同学聊天,发现他是在从事交互设计(我一点也不了解这是什么样的岗位),于是乎,我就想爬取下前程无忧网(招聘网_人才网_找工作_求职_上前程无忧)上的交互设计的岗位需求:

2实现过程

我这里使用scrapy框架来进行爬取。 2.1程序结构

C:\\Users\\hyperstrong\\spiderjob_jiaohusheji │scrapy.cfg │

└─spiderjob │ items.py

│ pipelines.py │ settings.py │ __init__.py

│ middlewares.py ├─spiders

│ jobSpider.py │ __init__.py

其中:

 

items.py是从网页抽取的项目 jobSpider.py是主程序

2.2链接的构造

用浏览器打开前程无忧网站 招聘网_人才网_找工作_求职_上前程无忧,在职务搜索里输入“交互设计师”,搜索出页面后,观察网址链接: 【交互设计师招聘】前程无忧手机网_触屏版

http://search.51job.com/jobsearch/search_result.php?fromJs=1&keyword=%E4%BA%A4%E4%BA%92%E8%AE%BE%E8%AE%A1%E5%B8%88&keywordtype=2&lang=c&stype=2&postchannel=0000&fromType=1&confirmdate=9

网址链接中并没有页码,于是选择第二页,观察链接:

红色标记的为页码,于是可以通过更改此处数字来实现从“第1页”到第44页“的网页自动跳转。当然读者也可以通过网页内容抓取处下一页的链接进行自动翻页,有兴趣的网友可以试下:

2.3网页分析

我要抓取的几个数据分别是

  

职位名 公司名 工作地点

 

薪资 发布时间

截图如下,右侧是浏览器-开发者工具(F12)里查找的源代码,和网页对应查看:

2.4数据字段:items.py

# -*- coding: utf-8 -*-

# Define here the models for your scraped items # See documentation in:

# http://doc.scrapy.org/en/latest/topics/items.html

import scrapy

class SpiderjobItem(scrapy.Item):

# define the fields for your item here like: # name = scrapy.Field() jobname = scrapy.Field() companyname= scrapy.Field() workingplace= scrapy.Field() salary= scrapy.Field() posttime= scrapy.Field()

2.5主要运行程序

我是用的python2.7编写的,并且使用XPath表达式进行数据的筛选和提取。

# -*- coding: utf-8 -*- from scrapy import Request

from scrapy.spiders import Spider

from spiderjob.items import SpiderjobItem

class jobSpider(Spider): name = 'jobSpider' headers = {

'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.75 Safari/537.36 LBBROWSER',

'Accept':'text/css,*/*;q=0.1',

'Accept-Encoding':'gzip, deflate, sdch', 'Accept-Language':'zh-CN,zh;q=0.8', 'Referer':'close',

'Host':'js.51jobcdn.com'};

def start_requests(self): url1 =

'http://search.51job.com/list/000000,000000,0000,00,9,99,%25E4%25BA%25A4%25E4%25BA%2592%25E8%25AE%25BE%25E8%25AE%25A1%25E5%25B8%2588,2,' url2 =

'.html?lang=c&stype=1&postchannel=0000&workyear=99&cotype=99°reefrom=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=' url = url1 +'1'+ url2

yield Request(url, headers=self.headers)

def parse(self, response): item = SpiderjobItem() jobs =

response.xpath('//div[@class=\"dw_table\"]/div[@class=\"el\"]') for job in jobs:

item['companyname'] = job.xpath(

'.//span[@class=\"t2\"]/a[@target=\"_blank\"]/text()').extract()[0]

item['workingplace'] = job.xpath(

'.//span[@class=\"t3\"]/text()').extract()[0]

item['salary'] = job.xpath(

'.//span[@class=\"t4\"]/text()').extract()

item['posttime'] =

job.xpath('.//span[@class=\"t5\"]/text()').extract()[0] item['jobname'] = job.xpath( './/p[@class=\"t1

\"]/span/a[@target=\"_blank\"]/text()').extract()[0] yield item

for i in range(2,44): url1 =

'http://search.51job.com/list/000000,000000,0000,00,9,99,%25E4%25BA%25A4%25E4%25BA%2592%25E8%25AE%25BE%25E8%25AE%25A1%25E5%25B8%2588,2,'

url2 =

'.html?lang=c&stype=1&postchannel=0000&workyear=99&cotype=99°reefrom=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='

next_url = url1 +str(i)+ url2

yield Request(next_url,

headers=self.headers,callback=self.parse)

2.6抓取效果:

在开始运行里输入里cmd,修改路径为

C:\\Users\\hyperstrong\\spiderjob_jiaohusheji 。然后输入scrapy crawl jobSpder -o jiaohusheji.csv

3数据进行简单分析

  

从excel表格里抽取2个特征:薪资和城市 分析不同城市的交互设计岗位 平均薪资

分析不同城市对于交互设计岗位需求,即在该城市是否容易找到工作

说干就干,代码奉上:

#!/usr/bin/python

# -*- coding: UTF-8 -*-

import pandas as pd import numpy as np

from datetime import datetime import matplotlib.pyplot as plt import sys import re import csv import string

def analyze_job_demand (filepath): data = pd.read_csv(filepath) wp=[]

num=len(data['workingplace']) for i in range(0,num-1):

a=data['workingplace'].ix[i].decode('utf-8') b=a[0:2].encode('utf-8') wp.append(b) bj=wp.count('北京') sh=wp.count('上海') gz=wp.count('广州') sz=wp.count('深圳') wh=wp.count('武汉') cd=wp.count('成都') cq=wp.count('重庆') zz=wp.count('郑州') nj=wp.count('南京') sz1=wp.count('苏州') hz=wp.count('杭州')

xa=wp.count('西安') dl=wp.count('大连') qd=wp.count('青岛') cs=wp.count('长沙') nc=wp.count('南昌') hf=wp.count('合肥') nb=wp.count('宁波') km=wp.count('昆明')

last=num-bj-sh-gz-sz-wh-cd-cq-nj-sz1-hz-xa-cs-hf

print( u'武汉的交互设计相关岗位占全国的需求比例为:' + str(float(wh)/num*100)+'%')

print( u'苏州的交互设计相关岗位占全国的需求比例为:' + str(float(sz1)/num*100)+'%')

print( u'杭州的交互设计相关岗位占全国的需求比例为:' + str(float(hz)/num*100)+'%')

print( u'合肥的交互设计相关岗位占全国的需求比例为:' + str(float(hf)/num*100)+'%')

print( u'长沙的交互设计相关岗位占全国的需求比例为:' + str(float(cs)/num*100)+'%')

print( u'北京的交互设计相关岗位占全国的需求比例为:' + str(float(bj)/num*100)+'%')

print( u'上海的交互设计相关岗位占全国的需求比例为:' + str(float(sh)/num*100)+'%')

print( u'广州的交互设计相关岗位占全国的需求比例为:' + str(float(gz)/num*100)+'%')

print( u'深圳的交互设计相关岗位占全国的需求比例为:' + str(float(sz)/num*100)+'%')

print( u'重庆的交互设计相关岗位占全国的需求比例为:' + str(float(cq)/num*100)+'%')

print( u'成都的交互设计相关岗位占全国的需求比例为:' + str(float(cd)/num*100)+'%')

print( u'南京的交互设计相关岗位占全国的需求比例为:' + str(float(nj)/num*100)+'%')

print( u'西安的交互设计相关岗位占全国的需求比例为:' + str(float(xa)/num*100)+'%')

#绘制饼图

#调节图形大小,宽,高

plt.figure(figsize=(6,9)) #定义饼状图的标签,标签是列表 labels =

['shanghai','shenzhen','beijing','guangzhou','hangzhou','wuhan

','chengdu','chongqing','nanjing','suzhou','xian','changsha','hefei','else']

sizes = [sh,sz,bj,gz,hz,wh,cd,cq,nj,sz1,xa,cs,hf,last] colors =

['red','yellowgreen','lightskyblue','blue','pink','coral','orange']

#将某部分爆炸出来, 使用括号,将第一块分割出来,数值的大小是分割出来的与其他两块的间隙

explode = (0.05,0,0,0,0,0,0,0,0,0,0,0,0,0) patches,l_text,p_text =

plt.pie(sizes,explode=explode,labels=labels,colors=colors, labeldistance = 1.1,autopct = '%3.1f%%',shadow = False,

startangle = 90,pctdistance = 0.6)

#labeldistance,文本的位置离远点有多远,1.1指1.1倍半径的位置 #autopct,圆里面的文本格式,%3.1f%%表示小数有三位,整数有一位的浮点数

#shadow,饼是否有阴影

#startangle,起始角度,0,表示从0开始逆时针转,为第一块。一般选择从90度开始比较好看

#pctdistance,百分比的text离圆心的距离

#patches, l_texts, p_texts,为了得到饼图的返回值,p_texts饼图内部文本的,l_texts饼图外label的文本 #改变文本的大小

#方法是把每一个text遍历。调用set_size方法设置它的属性 for t in l_text: t.set_size=(30) for t in p_text: t.set_size=(40)

# 设置x,y轴刻度一致,这样饼图才能是圆的 plt.axis('equal')

#图形中的文字无法通过rcParams设置 plt.legend() plt.show()

def analyze_salary(filepath): data = pd.read_csv(filepath)

chengshi=[u'北京',u'上海',u'广州',u'深圳',u'武汉',u'成都',u'重庆',u'郑州',u'南京',u'苏州',u'杭州',u'西安',u'大连',u'青岛',u'长沙',u'南昌',u'合肥',u'宁波',u'昆明'] city_salary=[] salary=[]

num=len(data['workingplace']) for j in range(0,18): city=chengshi[j]

for i in range(0,num-1):

a=data['workingplace'].ix[i].decode('utf-8') if a.find(city)!=-1:

if data['salary'].ix[i] :

c=str(data['salary'].ix[i]) d=c.decode('utf-8')

if d.find(u'万/月')!=-1:

pattern=re.compile('\\d+\\.?\\d*',re.S) items = re.findall(pattern,c)

ave=(float(items[0])+float(items[1]))/2 sal=float(ave)*10

elif d.find(u'千/月')!=-1:

pattern=re.compile('\\d+\\.?\\d*',re.S) items = re.findall(pattern,c)

ave=(float(items[0])+float(items[1]))/2 sal=float(ave)*1

elif d.find(u'万/年')!=-1:

pattern=re.compile('\\d+\\.?\\d*',re.S) items = re.findall(pattern,c)

ave=(float(items[0])+float(items[1]))/2 sal=float(ave)*0.8333 salary.append(sal)

ave=sum(salary)/len(salary)

print( chengshi[j] +u'的交互设计相关岗位的平均工资为:' + str(ave) +u'千/月')

city_salary.append(ave) salary=[] with

open('C:\\Users\\hyperstrong\\spiderjob_jiaohusheji\\salary.csv', 'wb') as f:

writer = csv.writer(f) chengshi_encode=[] for k in range(0,18):

chengshi_encode.append(chengshi[k].encode('utf-8')) writer.writerow(chengshi_encode) writer.writerow(city_salary) f.close()

if __name__ == '__main__':

filepath = input('Please enter the filename:') analyze_salary(filepath)

analyze_job_demand (filepath)

运行程序,输入excel的路径:

r'C:\\Users\\hyperstrong\\spiderjob_jiaohusheji\\jiaohusheji.csv'(注意路径前加 r,去掉转移字符) 效果如下:

不同城市的岗位需求量占全国总需求的比例,自动生产的饼图:

保存的excel绘制出不同城市的该岗位的平均薪资的柱状图,如下:

从以上几图可以看出:

1. 北京的交互设计平均工资最高

2. 杭州的交互设计需求和平均工资都已经是一线城市的水平,怪不得很多IT人才往杭

州跑

3. 江浙沪的需求量占了半壁江山

结束语

弄了这么半天,从城市需求、平均工资方面我已经对这个岗位有了初步认识。如果我是一个即将毕业并想从事该工作的大学生,看到这些,应该会有些帮助。不过实际选择会更加困难,不同的城市竞争是不一样的,房贷压力、幸福指数、城市的行业分布、城市未来发展潜力都不不一样。于是我想到:如何从不同城市各个行业求职情况,来看出城市的幸福指数、发展潜力。找个时间研究下~~~///(^v^)\\\\\\~~~

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- dfix.cn 版权所有 湘ICP备2024080961号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务