#通过输入的关键字,爬取北京地区某岗位的平均月薪
# -*- coding: utf-8 -*-
import re
import requests
import time
import lxml.html
from bs4 import BeautifulSoup
#------------------------------------------------定义函数:获取指定网页北京地区所有相关职位的月薪---------------------
def getSalary(url):
    headers = {"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36'}
    resp=requests.get(url,headers=headers)
    time.sleep(5)
    web_data = BeautifulSoup(resp.content, "lxml")
    firstlist=web_data.find_all('td')
    salarylist1=[]
    salarylist2=[]
    for i in firstlist:
        if 'zwyx' in str(i) and '面议' not in str(i):    #提取职位月薪,并存入salarylist1列表,月薪为面议时不统计
            salarylist1.append(str(i))                       #将列表转为字符串,并用正则表达式提取字符串里面的数字(即月薪),并存入salarylist2,此时列表中元素格式还是字符串
    salaryliststr='+'.join(salarylist1)
    reeq=re.compile(r'(\w[0-9]+)\w*')
    salarylist2=re.findall(reeq,salaryliststr)
    salarylist2=map(float,salarylist2)                       #将字符串格式的月薪转为float型
    return salarylist2                                      #以数字列表形式返回指定网页所有统计到的月薪
#-------------------------定义函数:统计智联招聘网站北京地区,招聘岗位名称包含keyword关键字所有岗位的平均月薪-------------
def getAverageSalary(keyword):
    url=r'http://sou.zhaopin.com/jobs/searchresult.ashx?jl=%E5%8C%97%E4%BA%AC&kw='+keyword+'&sm=0&p=1&kt=3'  #包含关键字的网站名
    headers = {"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36'}
    pagelist=[]
    salarylist=getSalary(url)         #提取第一页的招聘岗位月薪信息,并存入salarylist列表
    print salarylist
    while True:
        resp=requests.get(url,headers=headers)
        time.sleep(5)
        if resp.status_code!=200:
            break
        resp=resp.content
        reg=r'a href="(.*?)" class="next-page">下一页</a>'         #用于获取下一页地址的正则表达式
        reg=re.compile(reg)
        page=re.findall(reg,resp)
        if page!=[]:                                                      #如果未到检索的最后一页
            page1=re.split(r'href="',page[0])                             #提取当前页的下一页的网址,并赋给url
            if re.search('http',page1[-1]):
                pagelist.append(page1[-1])
                url=page1[-1]
                salarylist2=getSalary(url)
                #print 'salarylist',salarylist
                salarylist.extend(salarylist2)                          #将新提取的月薪信息存入salarylist列表
                #print 'salarylist2',salarylist
            else:
                break
        else:                                                              #已到检索到的最后一页,结束循环
            break
    salarylist=map(float,salarylist)
    if len(salarylist)!=0:
        averageSalary=sum(salarylist)/len(salarylist)
        return averageSalary,pagelist
    else:
        print '统计到的月薪列表为0,请检查网页是否正确!'
        return 0,[0,]

averageSalary,pagelist=getAverageSalary('CAE')     #爬取关键字为 CAE 的岗位平均月薪
print 'AverageSalary:',averageSalary