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链接的构造用浏览器打开前程无忧网站 招聘网_人才网_找工作_求职_上前程无忧,在职务搜索里输入“交互设计师”,搜索出页面后,观察网址链接:【交互设计师招聘】前程无忧手机网_触屏版/jobsearch/search_result.php?fromJs=1&k eyword=%E4%BA%A4%E4%BA%92%E8%AE%BE%E8%AE%A1%E5%B8%88&keywordty pe=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:# /en/latest/topics/items.htmlimport scrapyclass 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 Requestfrom scrapy.spiders import Spiderfrom spiderjob.items import SpiderjobItemclass jobSpider(Spider):name ='jobSpider'headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) 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':''};def start_requests(self):url1 ='/list/000000,000000,0000,00,9,99,%25E4 %25BA%25A4%25E4%25BA%2592%25E8%25AE%25BE%25E8%25AE%25A1%25E5%2 5B8%2588,2,'url2 ='.html?lang=c&stype=1&postchannel=0000&workyear=99&cotype=99&d egreefrom=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'+ url2yield 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 itemfor i in range(2,44):url1 ='/list/000000,000000,0000,00,9,99,%25E4 %25BA%25A4%25E4%25BA%2592%25E8%25AE%25BE%25E8%25AE%25A1%25E5%2 5B8%2588,2,'url2 ='.html?lang=c&stype=1&postchannel=0000&workyear=99&cotype=99&d egreefrom=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)+ url2yield Request(next_url,headers=self.headers,callback=self.parse)2.6抓取效果:在开始运行里输入里cmd,修改路径为C:\Users\hyperstrong\spiderjob_jiaohusheji 。
然后输入scrapy crawl jobSpder -o jiaohusheji.csv3数据进行简单分析从excel表格里抽取2个特征:薪资和城市分析不同城市的交互设计岗位 平均薪资分析不同城市对于交互设计岗位需求,即在该城市是否容易找到工作说干就干,代码奉上:#!/usr/bin/python# -*- coding: UTF-8 -*-import pandas as pdimport numpy as npfrom datetime import datetimeimport matplotlib.pyplot as pltimport sysimport reimport csvimport stringdef 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','ora nge']#将某部分爆炸出来,使用括号,将第一块分割出来,数值的大小是分割出来的与其他两块的间隙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开始逆时针转,为第一块。