10,zzlian爬取

职位属性分析

json

根据XHR获取的数据json

##获取地址
https://fe-api.zhaopin.com/c/i/sou?_v=0.28738099&x-zp-page-request-id=a1fb0e55ab9d4e86a00b25196e43c513-1579506475680-740213&x-zp-client-id=29f9e81e-3733-4572-8a33-ca68d5b88756&MmEwMD=4efyZZIZT80QYGAdVyXLr9sDoMwds3_bolcL84cEscxp6pHfh74Agw3_jog9XrpsFwdVMRNFUw8.B0fvxET6WamFePgwwM7xUjMgS4nMaNqzt.XSBzZCFtQMkDvAAda.tFdJxLEIdBN7Yvq4_nORcWGGY6Yd_nRozG2hjK2HqU8.ZFuql3hSlnQ8HCuOqtqcKkXHuV_5zZwijcaaYYsTZE8NNxQ9ssJWf3SF5wWoyd_8mCGNQwL9RG_dILT4i4IbJiymYoF9R6xmqJQlFghUocsCfWHuRgmW6RfeqDFgZ4DhDNAlpB2vIOXeFuoxaNLfIsE.ckUH9RPsFonCageEB_pK6cCtbEPx2mTQZpGEj5rLOndIsdat8oZNkMsZzY5YXXmsyjOSXrNLyOno3uNEs2Fkt

##使用


{
                "number": "CC892755990J00199427109", 
                "jobName": "Python 工程师", 
                "company": {
                    "name": "人民中科(山东)智能技术有限公司北京分公司", 
                    "number": "CZ892755990", 
                    "type": {
                        "name": "其它"
                    }, 
                    "size": {
                        "name": "20-99人"
                    }, 
                    "url": "https://company.zhaopin.com/CZ892755990.htm"
                }, 
                "city": {
                    "items": [
                        {
                            "name": "北京", 
                            "code": "530"
                        }
                    ], 
                    "display": "北京"
                }, 
                "updateDate": "2020-01-20 00:50:15", 
                "salary": "13K-20K", 
                "distance": 0, 
                "eduLevel": {
                    "name": "大专"
                }, 
                "jobType": {
                    "items": [
                        {
                            "name": "软件/互联网开发/系统集成"
                        }
                    ]
                }, 
                "feedbackRation": 0, 
                "workingExp": {
                    "name": "5-10年"
                }, 
                "industry": "160000,160200,160400,160100", 
                "emplType": "全职", 
                "applyType": "1", 
                "saleType": false, 
                "positionURL": "https://jobs.zhaopin.com/CC892755990J00199427109.htm", 
                "companyLogo": "https://rd5-public.zhaopin.cn/imgs/company/02a6367fc16ffe109ae696455760b38c.jpg", 
                "tags": [ ], 
                "expandCount": 0, 
                "score": "580", 
                "vipLevel": 1002, 
                "positionLabel": "{"chatWindow":null,"refreshLevel":2,"skillLabel":[{"state":0,"value":"MySQL"},{"state":0,"value":"Python"},{"state":0,"value":"分布式视频编解码系统"}]}", 
                "bestEmployerLabel": [ ], 
                "welfare": [    #福利
                    "五险一金", 
                    "年底双薪", 
                    "绩效奖金", 
                    "带薪年假", 
                    "弹性工作"
                ], 
                "businessArea": "五道口", 
                "futureJob": false, 
                "futureJobUrl": "", 
                "tagIntHighend": 0, 
                "rootOrgId": 89275599, 
                "staffId": 1045581628, 
                "chatWindow": 0, 
                "batchDeliveryType": 1, 
                "index": 5, 
                "selected": false, 
                "applied": false, 
                "collected": false, 
                "isShow": false, 
                "timeState": "最新", 
                "rate": ""
            }, 

数据获取(浏览器)

可以使用无头浏览器获取数据

##职位概述
<h3 class="summary-plane__title">Python 工程师</h3>

<div class="summary-plane__bottom">
    <div class="summary-plane__left">
        <span class="summary-plane__salary">
            1.3万-2万
        </span>
        <a href="https://www.zhaopin.com/gz_beijing/" target="_blank" class="summary-plane__calc">
            <i class="iconfont icon-calculator">
            </i>
        </a>
        <ul class="summary-plane__info">
            <li>
                <a href="//www.zhaopin.com/beijing/" target="_blank">
                    北京
                </a>
            </li>
            <li>
                5-10年
            </li>
            <li>
                大专
            </li>
            <li>
                招2人
            </li>
        </ul>
    </div>
</div>





##职位细节
<div class="job-detail">
    <div class="highlights">
        <h2 class="highlights__title">
            职位亮点
        </h2>
        <div class="highlights__content">
            <span class="highlights__content-item">
                五险一金
            </span>
            <span class="highlights__content-item">
                年底双薪
            </span>
            <span class="highlights__content-item">
                绩效奖金
            </span>
            <span class="highlights__content-item">
                带薪年假
            </span>
            <span class="highlights__content-item">
                弹性工作
            </span>
            <span class="highlights__content-item">
                补充医疗保险
            </span>
            <span class="highlights__content-item">
                定期体检
            </span>
        </div>
    </div>
    <!---->
    <div class="describtion">
        <h2 class="describtion__title">
            职位描述
        </h2>
        <div class="describtion__skills">
            <div class="describtion__skills-title">
                技能要求:
            </div>
            <div class="describtion__skills-content">
                <span class="describtion__skills-item">
                    MySQL
                </span>
                <span class="describtion__skills-item">
                    Python
                </span>
                <span class="describtion__skills-item">
                    分布式视频编解码系统
                </span>
            </div>
        </div>
        <div class="describtion__detail-content">
            岗位职责:
            <br>
            1、负责视频转解码开发工作;
            <br>
            2、负责业务系统数据分流中心开发工作;
            <br>
            任职条件:
            <br>
            1、全职类工作4(包含) 年以上开发经验;
            <br>
            2、Python基础扎实,掌握常用的类库的使用;
            <br>
            3、熟悉关系型数据库、非关系型数据库原理,如Mysql、REDIS等。(必须)
            <br>
            4、必须对多线程、分布式编程有较强的实践和应用能力。
            <br>
            5、掌握KAFKA、MQ等常用消息队列的使用。
            <br>
            6、熟悉Linux基本操作和常用命令,有Java开发经验优先。
            <br>
            7、熟悉基于FFMPEG的视频处理技术优先。
            <br>
            8、具有优秀的团队合作和独立抗压能力,善于学习,乐于分享。
            <br>
        </div>
    </div>
    <div class="job-address clearfix">
        <h2 class="job-address__title">
            工作地点
        </h2>
        <div class="job-address__content">
            <span class="job-address__content-text">
                <i class="iconfont icon-locate">
                </i>
                海淀区中关村东路66号世纪科贸大厦B座2705
            </span>
            <button class="job-address__content-view-map-button">
                查看地图
            </button>
            <div id="address__mapContainer" class="job-address__content-map" style="display:none;">
            </div>
        </div>
    </div>
</div>

使用工具获取数据

##获取职位名称   title
//*[@id="root"]/div[3]/div[1]/div/h3



##获取薪资   salary
//*[@id="root"]/div[3]/div/div/div[2]/div[1]/span


##info
//*[@id="root"]/div[3]/div/div/div[2]/div[1]/ul   获取其下的信息(地点,北京, 3-5年, 学历,招人数量)



##职位亮点
//*[@id="root"]/div[4]/div[1]/div[1]/div[1]/div  


##技能要求
//*[@id="root"]/div[4]/div[1]/div[1]/div[2]/div[1]/div[2]


##职位描述
//*[@id="root"]/div[4]/div[1]/div[1]/div[2]/div[2]

##工作地点
//*[@id="root"]/div[4]/div[1]/div[1]/div[3]/h2

操作流程

1,获取url(无头浏览器)

https://sou.zhaopin.com/?jl=530&kw=Python&kt=3


在此页面下获取每一个职位的url并保存,一共可以获取3页   每页的前三为广告,去除 
//*[@id="listContent"]/div[3]/div/a   的href=""



2,根据每个url 去获取他的职位细节

获取职位数据

考虑将无头浏览器的功能封装到一个类里面使用

4,保存数据

以什么格式保存,后期可以随时获取分析,保存的时候以时间点为轴,可以获取

保存时候薪水取最低的数字

使用mongodb  数据库

热门地点:

北京   上海   深圳 广州 天津  成都 杭州 武汉  大连   长春  南京 济南 青岛  苏州   沈阳 西安 郑州 长沙  重庆  哈尔滨  无锡  宁波  福州  厦门  石家庄  合肥  惠州  

分析参考链接

https://zhuanlan.zhihu.com/p/48349379   
https://zhuanlan.zhihu.com/p/27792227


https://blog.csdn.net/lys1695227550/article/details/82730024  有仓库 https://github.com/cherise-lailai/pythonRepository.git



https://www.jianshu.com/p/64dad9fb5c59  有原始数据可下载

selenium firefox

谷歌浏览器无法打开智联,使用firefox 可以正常

安装https://github.com/mozilla/geckodriver/releases

智联测试

driver = webdriver.Firefox()
driver.get("https://sou.zhaopin.com/?jl=530&kw=Python&kt=3")
driver.refresh() #刷新弹出的窗口
driver.fullscreen_window()



##测试
jobitems = driver.find_elements_by_class_name("contentpile__content__wrapper__item")
type(jobitems)
<class 'list'>
jobitems[0].text
'大数据分析工程师
立即沟通

银清科技有限公司
20K-30K
北京-海淀区
3-5年
本科
国企 500-999人
五险一金
年底双薪
绩效奖金
带薪年假
补充医疗保险
招聘中'
jobitems[1].text
'Python全栈开发
立即沟通

元素征信有限责任公司
30K-50K
北京
5-10年
本科
民营 20-99人
求贤若渴
五险一金
定期体检
员工旅游
节日福利
带薪年假
最新'
for i in jobitems:
    print(i.text)
    

    
##获取信息   
jobitems[4].text.replace("
", " ").split(sep=" ")
['Python开发工程师', '立即沟通', '', '北京富益辰医疗科技有限公司', '10K-20K', '北京', '3-5年', '大专', '民营', '20-99人', '五险一金', '股票期权', '弹性工作', '创业公司', '项目奖金', '最新']
jobitems[0].text.replace("
", " ").split(sep=" ")
['大数据分析工程师', '立即沟通', '', '银清科技有限公司', '20K-30K', '北京-海淀区', '3-5年', '本科', '国企', '500-999人', '五险一金', '年底双薪', '绩效奖金', '带薪年假', '补充医疗保险', '招聘中']
jobitems[1].text.replace("
", " ").split(sep=" ")
['Python全栈开发', '立即沟通', '', '元素征信有限责任公司', '30K-50K', '北京', '5-10年', '本科', '民营', '20-99人', '求贤若渴', '五险一金', '定期体检', '员工旅游', '节日福利', '带薪年假', '最新']
jobitems[2].text.replace("
", " ").split(sep=" ")
['Python工程师', '立即沟通', '', '北京康信知识产权代理有限责任公司', '10K-20K', '北京', '3-5年', '硕士', '民营', '100-499人', '同事很nice', '工作环境好', '氛围活跃', '团队执行强', '交通便利', '最新']

删除空格
itemtemp = ['Python开发工程师', '立即沟通', '', '北京富益辰医疗科技有限公司', '10K-20K', '北京', '3-5年', '大专', '民营', '20-99人', '五险一金', '股票期权', '弹性工作', '创业公司', '项目奖金', '最新']
item = [i for i in itemtemp if i != ""]


jjob = []
for i in jobitems:
    jjob.append(i.text.replace("
", " ").split(sep=" "))



每页一共90个链接
##获取job urls
aurls = driver.find_elements_by_xpath('//*[@id="listContent"]/div/div/a')
for url in aurls:
    print(url.get_attribute("href"))
    
jurls = []
for i in aurls:
    jurls.append(i.get_attribute("href"))


##获取公司url  
companyurls = driver.find_elements_by_xpath('//*[@id="listContent"]/div/div/a/div[1]//a')
for url in companyurls:
    print(url.get_attribute("href"))
    
jcomurls = []
for url in companyurls:
    jcomurls.append(url.get_attribute("href"))
    
    
    
tt = zip(jjob, jurls, jcomurls)
for i in tt:
    print(i)
    
(['大数据分析工程师', '立即沟通', '', '银清科技有限公司', '20K-30K', '北京-海淀区', '3-5年', '本科', '国企', '500-999人', '五险一金', '年底双薪', '绩效奖金', '带薪年假', '补充医疗保险', '招聘中'], 'https://jobs.zhaopin.com/CC120072300J00203379213.htm', 'http://special.zhaopin.com/pagepublish/12007230/index.html')
(['Python全栈开发', '立即沟通', '', '元素征信有限责任公司', '30K-50K', '北京', '5-10年', '本科', '民营', '20-99人', '求贤若渴', '五险一金', '定期体检', '员工旅游', '节日福利', '带薪年假', '最新'], 'https://jobs.zhaopin.com/CC406602384J00213628512.htm', 'https://company.zhaopin.com/CZ406602380.htm')
(['Python工程师', '立即沟通', '', '北京康信知识产权代理有限责任公司', '10K-20K', '北京', '3-5年', '硕士', '民营', '100-499人', '同事很nice', '工作环境好', '氛围活跃', '团队执行强', '交通便利', '最新'], 'https://jobs.zhaopin.com/CC000127437J00188500912.htm', 'https://special.zhaopin.com/pagepublish/12743/index.html')
(['Python', '立即沟通', '', '北京阿提拉科技有限公司', '10K-15K', '北京', '经验不限', '学历不限', '民营', '100-499人', '最新'], 'https://jobs.zhaopin.com/CC147646001J00153835513.htm', 'https://company.zhaopin.com/CZ147646000.htm')
(['Python研发工程师', '立即沟通', '', '北京玖月奇迹文化传播有限公司', '15K-20K', '北京', '1-3年', '本科', '民营', '20-99人', '带薪年假', '节日福利', '绩效奖金', '五险一金', '年终分红', '最新'], 'https://jobs.zhaopin.com/CC319091521J00257477011.htm', 'https://company.zhaopin.com/CZ319091520.htm')
(['Python软件开发/.net软件开发', '立即沟通', '', '北京丽盛创盈科技有限公司', '2K-4K', '北京', '无经验', '本科', '民营', '20人以下', '求贤若渴', '绩效奖金', '弹性工作', '带薪年假', '餐补', '项目奖金', '最新'], 'https://jobs.zhaopin.com/CC411991921J00208450315.htm', 'https://company.zhaopin.com/CZ411991920.htm')
(['Python研发工程师', '立即沟通', '', '北京安信天行科技有限公司', '8K-10K', '北京', '无经验', '本科', '国企', '500-999人', '求贤若渴', '五险一金', '交通补助', '通讯补助', '带薪年假', '补充医疗保险', '最新'], 'https://jobs.zhaopin.com/CC323676912J00208245715.htm', 'https://company.zhaopin.com/CZ323676910.htm')
(['Python开发工程师', '立即沟通', '', '北京数创世纪软件技术有限公司', '8K-15K', '北京', '经验不限', '大专', '民营', '20-99人', '最新'], 'https://jobs.zhaopin.com/CC179463422J00231581010.htm', 'https://company.zhaopin.com/CZ179463420.htm')
(['中级', 'Python', '开发工程师', '立即沟通', '', '广州市通证科技有限公司', '15K-25K', '北京-朝阳区', '3-5年', '本科', '民营', '20-99人', '求贤若渴', '弹性工作', '绩效奖金', '五险一金', '年终分红', '全勤奖', '最新'], 'https://jobs.zhaopin.com/CC713032630J00375011608.htm', 'https://company.zhaopin.com/CZ713032630.htm')
(['Python开发工程师', '立即沟通', '', '北京富益辰医疗科技有限公司', '10K-20K', '北京', '3-5年', '大专', '民营', '20-99人', '五险一金', '股票期权', '弹性工作', '创业公司', '项目奖金', '最新'], 'https://jobs.zhaopin.com/CC817853350J00212879211.htm', 'https://company.zhaopin.com/CZ817853350.htm')
(['Python开发工程师', '立即沟通', '', '中国电信股份有限公司云计算分公司', '20K-40K', '北京', '5-10年', '本科', '国企', '100-499人', '工作环境好', '同事很nice', '人际关系好', '招聘中'], 'https://jobs.zhaopin.com/CC469890314J00097657814.htm', 'http://special.zhaopin.com/bj/2012/dxyjs051152/index.html')
(['遥感算法(C/C++、Python)-气象、生态遥感', '立即沟通', '', '中科星图股份有限公司', '13K-25K', '北京-海淀区', '1-3年', '硕士', '股份制企业', '500-999人', '节日福利', '工作居住证', '全额公积金', '试用期全额', '住房补贴', '最新'], 'https://jobs.zhaopin.com/CC142710115J00123274915.htm', 'http://special.zhaopin.com/pagepublish/14271011/index.html')
(['Python开发工程师', '立即沟通', '', '京北方信息技术股份有限公司', '10K-15K', '北京', '5-10年', '本科', '民营', '10000人以上', '同事很nice', '工作环境好', '人际关系好', '氛围活跃', '团队执行强', '招聘中'], 'https://jobs.zhaopin.com/CC315847111J00199791113.htm', 'https://company.zhaopin.com/CZ315847110.htm')
(['Python高级爬虫工程师', '立即沟通', '', '天宇正清科技有限公司', '12K-20K', '北京', '3-5年', '本科', '民营', '100-499人', '五险一金', '员工旅游', '节日福利', '不加班', '带薪年假', '最新'], 'https://jobs.zhaopin.com/CC173534914J00200697110.htm', 'https://company.zhaopin.com/CZ173534910.htm')
(['Python开发工程师', '立即沟通', '', '绫致时装(天津)有限公司/Bestseller', 'Fashion', 'Group', '(Tianjin)', 'Co.,Ltd', '薪资面议', '北京', '5-10年', '本科', '外商独资', '10000人以上', '工作环境好', '氛围活跃', '同事很nice', '团队执行强', '准时发工资', '最新'], 'https://jobs.zhaopin.com/CC000423265J00085223913.htm', 'http://special.zhaopin.com/bj/2010/lzsz032322/index.htm')
(['【腾讯云】Python后端开发工程师', '立即沟通', '', '中软国际科技服务有限公司', '薪资面议', '北京-昌平区', '3-5年', '本科', '上市公司', '10000人以上', '五险一金', '年底双薪', '绩效奖金', '加班补助', '全勤奖', '招聘中'], 'https://jobs.zhaopin.com/CC508620126J00448682605.htm', 'https://company.zhaopin.com/CZ508620120.htm')
(['高级C/C++/Python开发工程师', '立即沟通', '', '北京霍因科技有限公司', '20K-30K', '北京', '3-5年', '本科', '民营', '20-99人', '五险一金', '绩效奖金', '股票期权', '带薪年假', '弹性工作', '最新'], 'https://jobs.zhaopin.com/CC608050080J00210443014.htm', 'https://company.zhaopin.com/CZ608050080.htm')
(['Python高级/资深开发工程师', '立即沟通', '', '郑州米巢信息技术有限公司', '20K-30K', '北京', '1-3年', '本科', '民营', '100-499人', '五险一金', '年底双薪', '绩效奖金', '加班补助', '餐补', '最新'], 'https://jobs.zhaopin.com/CCL1227383970J00220144214.htm', 'https://company.zhaopin.com/CZL1227383970.htm')
(['高薪/Python开发工程师', '立即沟通', '', '郑州龙格信息科技有限公司', '15K-20K', '北京', '1-3年', '本科', '民营', '20-99人', '五险一金', '年底双薪', '绩效奖金', '年终分红', '带薪年假', '最新'], 'https://jobs.zhaopin.com/CCL1227389160J00207176315.htm', 'https://company.zhaopin.com/CZL1227389160.htm')  



##### 插入mogodb 的数据的  _id 是唯一值,如果重复插入,那么就会报错.

pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection: zhilian.test index: _id_ dup key: { _id: "python实习1" }

根据特定值查询后结果为
query = {"_id": "python实习1"}
col = mydoc.find(query)
type(col)
<class 'pymongo.cursor.Cursor'>

该查询游标类型只能使用一次,如果再次递归打印需要再次查找
for i in col:
    print(i)
    
    
col = mydoc.find(query)
for i in col:
    print(i)
    print(type(i))
    
{'_id': 'python实习1', 'salary': '4K-5K', 'address': '北京海淀区', 'workingExp': '无经验', 'eduLevel': '本科', 'welfare': '求贤若渴 弹性工作 远程办公 公司重点项目', 'company': {'name': '北京掌控世代科技有限公司1', 'type': '民营', 'size': '20-99人', 'url': 'https://company.zhaopin.com/CZ241742980.htm'}, 'plan': '招1人', 'job_highlights': '弹性工作 远程办公 公司重点项目', 'job_describtion': '', 'job_address': '海淀区上地东路1号盈创动力E座302A', 'crawltime': '20200216'}
<class 'dict'>




对已经获取的网页源码使用beautifulsoup 获取数据

##保存网页源码
import pymongo
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("https://sou.zhaopin.com/?jl=530&kw=Python&kt=3")
driver.page_source  
f = open("/home/baixiaoxu/desk/zhilian.html", "w")
f.write(driver.page_source)


from bs4  import BeautifulSoup
soup = BeautifulSoup(open("/home/baixiaoxu/desk/zhilian.html"), "html.parser")




#################################################################################
from bs4 import  BeautifulSoup
soup = BeautifulSoup(open("/home/baixiaoxu/desk/zhilian.html"), "html.parser")
jobitemstemp = soup.select(".contentpile__content__wrapper__item")  ##获取job div  块共90 个 列表
len(jobitemstemp)   90 

#jobname
jobitemstemp[0].select_one(".contentpile__content__wrapper__item__info__box__jobname__title").get_text().strip().replace(' ','') '大数据分析工程师'
#公司名称
jobitemstemp[0].select_one(".contentpile__content__wrapper__item__info__box__cname__title").get_text().strip().replace(' ','')
#获取joburl
jobitemstemp[0].select_one('a[href^="https://jobs.zhaopin.com/"]').attrs["href"]  #或
jobitemstemp[0].select_one("a[class='contentpile__content__wrapper__item__info']").attrs["href"]
#  和公司url 
jobitemstemp[0].find('a', attrs={"class": "contentpile__content__wrapper__item__info__box__cname__title"}).attrs["href"]

##公司区域
jobitemstemp[0].select_one(".contentpile__content__wrapper__item__info__box__job__demand__item").get_text().strip().replace('-', '').replace(' ', '')

#公司区域   经验  学历
quyu, exp, edu = [i.get_text().strip().replace(' ', '')  for i in jobitemstemp[0].select(".contentpile__content__wrapper__item__info__box__job__demand__item")]
quyu
'北京-海淀区'
exp
'3-5年'
edu
'本科'


#公司性质
jobitemstemp[0].select_one(".contentpile__content__wrapper__item__info__box__job__comdec__item").get_text().strip() 
国企
#公司规模
[i.get_text().strip() for i in jobitemstemp[0].select(".contentpile__content__wrapper__item__info__box__job__comdec__item")]
['国企', '500-999人']


##公司福利
jobitemstemp[0].select_one(".job_welfare").get_text().strip()

爬取数据存储第一版

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2/19/20 2:24 PM
# @Author  : yon
# @Email   : 0@qq.com
# @File    : mongodb.py


import json
import time
import pymongo
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

class HandleMongodb(object):
    def __init__(self, ip, name, col):
        self.dbaddress = 'mongodb://{}:27017/'.format(ip)
        self.dbname = name
        self.dbcol = col
        self.doc = self.db_isexists()

    def db_isexists(self):
        try:
            myclient = pymongo.MongoClient(self.dbaddress)
            mydb = myclient[self.dbname]
            return mydb[self.dbcol]
        except Exception as e:
            raise Exception("ERROR :init db!")

    def insert_one(self, dic):
        try:
            result = self.doc.insert_one(dic)
            if result.inserted_id:
                return True
            else:
                return False
        except:
            return False

    def insert_many(self, dics):
        try:
            lens = len(dics)
            results = self.doc.insert_many(dics)
            if len(results.inserted_ids) == lens:
                return True
            else:
                return False
        except:
            return False

    def modify(self, query, tochange):
        # moodify one item
        newvalue = {"$set": tochange}
        modifyresult = self.doc.update_one(query, newvalue)
        if modifyresult.modified_count:
            return True
        else:
            return False

    def doc_isexists(self, dicisexists):
        # dicisexists = { "name": "RUNOOB" }
        if self.doc.find(dicisexists).count() > 0:
            return True
        else:
            return False

    def doccounts(self):
        return self.doc.count()


def crawlezhlian():
    dbip = "192.168.0.140"
    dbname = "zhilian"
    doc = "test"
    crawleurl = "https://sou.zhaopin.com/?jl=530&kw=Python&kt=3"
    crawleurls = [crawleurl, crawleurl + "&p=2", crawleurl + "&p=3"]
    mongodb_instance = HandleMongodb(dbip, dbname, doc)
    driver = webdriver.Firefox()
    for url in crawleurls:
        time.sleep(15)
        driver.get(url)
        driver.refresh()  # 刷新弹出的窗口
        driver.implicitly_wait(10)  # 隐式等待10s
        # driver.fullscreen_window()
        jobitemstemp = driver.find_elements_by_class_name("contentpile__content__wrapper__item")
        jobitems = [i.text.replace("
", " ").split(sep=" ") for i in jobitemstemp]
        joburlstemp = driver.find_elements_by_xpath('//*[@id="listContent"]/div/div/a')
        joburls = [url.get_attribute("href") for url in joburlstemp]
        companyurlstemp = driver.find_elements_by_xpath('//*[@id="listContent"]/div/div/a/div[1]//a')
        companyurls = [url.get_attribute("href") for url in companyurlstemp]
        itemstemp = zip(jobitems, joburls, companyurls)
        for itemtemp in itemstemp:
            itemtemplate = {'_id': itemtemp[0][3],
                            'jobname': itemtemp[0][0],
                            'salary': itemtemp[0][4],
                            'jobarea': itemtemp[0][5],
                            'workingExp': itemtemp[0][6],
                            'eduLevel': itemtemp[0][7],
                            'welfare': itemtemp[0][10:-2],
                            'company': {'name': itemtemp[0][3],
                                        'type': itemtemp[0][8],
                                        'size': itemtemp[0][9],
                                        'url': itemtemp[2],
                                        'job_address': '',
                                        },
                            'plan': '',
                            'job_highlights': '',
                            'job_describtion': '',
                            'crawltime': ''
                            }
            if mongodb_instance.insert_one(itemtemplate):
                print("{} 数据添加成功!".format(itemtemp[0][3]))
            else:
                print("{} 数据已存在!".format(itemtemp[0][3]))
    driver.close()


if __name__ == '__main__':
    crawlezhlian()


###################
问题:数据格式不纯净,导致保存有误,数据数量缺失


代码第二版

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2/19/20 2:24 PM
# @Author  : yon
# @Email   : @qq.com
# @File    : mongodb.py


import json
import time
import pymongo
from selenium import webdriver
from bs4 import BeautifulSoup
import time
class HandleMongodb(object):
    def __init__(self, ip, name, col):
        self.dbaddress = 'mongodb://{}:27017/'.format(ip)
        self.dbname = name
        self.dbcol = col
        self.doc = self.db_isexists()

    def db_isexists(self):
        try:
            myclient = pymongo.MongoClient(self.dbaddress)
            mydb = myclient[self.dbname]
            return mydb[self.dbcol]
        except Exception as e:
            raise Exception("ERROR :init db!")

    def insert_one(self, dic):
        try:
            result = self.doc.insert_one(dic)
            if result.inserted_id:
                return True
            else:
                return False
        except:
            return False

    def insert_many(self, dics):
        try:
            lens = len(dics)
            results = self.doc.insert_many(dics)
            if len(results.inserted_ids) == lens:
                return True
            else:
                return False
        except:
            return False

    def modify(self, query, tochange):
        # moodify one item
        newvalue = {"$set": tochange}
        modifyresult = self.doc.update_one(query, newvalue)
        if modifyresult.modified_count:
            return True
        else:
            return False

    def doc_isexists(self, dicisexists):
        # dicisexists = { "name": "RUNOOB" }
        if self.doc.find(dicisexists).count() > 0:
            return True
        else:
            return False

    def doccounts(self):
        return self.doc.count()


def crawlezhlian():
    dbip = "192.168.0.140"
    dbname = "zhilian"
    doc = "new"
    crawleurl = "https://sou.zhaopin.com/?jl=530&kw=Python&kt=3"
    # crawleurls = ["https://sou.zhaopin.com/?jl=530&kw=Python&kt=3", "https://sou.zhaopin.com/?p=2&jl=530&kw=Python", "https://sou.zhaopin.com/?p=3&jl=530&kw=Python&kt=3"]
    crawleurls = ["https://sou.zhaopin.com/?jl=530&kw=Python&kt=3", "https://sou.zhaopin.com/?p=2&jl=530&kw=Python&kt=3", "https://sou.zhaopin.com/?p=3&jl=530&kw=Python&kt=3"]
    mongodb_instance = HandleMongodb(dbip, dbname, doc)
    driver = webdriver.Firefox()
    for url in crawleurls:
        print("开始获取url {}".format(url))
        time.sleep(10)
        driver.get(url)  # 刷新弹出的窗口
        # driver.implicitly_wait(20)  # 隐式等待10s
        driver.refresh()
        driver.implicitly_wait(30)
        time.sleep(20)
        # driver.fullscreen_window()
        soup = BeautifulSoup(driver.page_source, "html.parser")
        jobitemstemp = soup.select(".contentpile__content__wrapper__item")
        for item in jobitemstemp:
            jobname = item.select_one(".contentpile__content__wrapper__item__info__box__jobname__title").get_text().strip().replace(' ', '')
            salary = item.select_one(".contentpile__content__wrapper__item__info__box__job__saray").get_text().strip()
            companyname = item.select_one(".contentpile__content__wrapper__item__info__box__cname__title").get_text().strip().replace(' ','')
            joburl = item.select_one("a[class='contentpile__content__wrapper__item__info']").attrs["href"]
            companyurl = item.find('a', attrs={"class": "contentpile__content__wrapper__item__info__box__cname__title"}).attrs["href"]
            companyarea, exp, edu = [i.get_text().strip().replace(' ', '') for i in item.select(".contentpile__content__wrapper__item__info__box__job__demand__item")]
            companytype, companysize = [i.get_text().strip() for i in item.select(".contentpile__content__wrapper__item__info__box__job__comdec__item")]
            try:
                welfare = item.select_one(".job_welfare").get_text().strip()
            except:
                print("{} {} 福利数据为空!".format(companyname, jobname))
                welfare = ""

            itemtemplate = {'jobname': jobname,
                            'salary': salary,
                            'jobarea': companyarea,
                            'workingExp': exp,
                            'eduLevel': edu,
                            'welfare': welfare,
                            'joburl': joburl,
                            'company': {'name': companyname,
                                        'type': companytype,
                                        'size': companysize,
                                        'url': companyurl,
                                        'job_address': '',
                                        },
                            'plan': '',
                            'job_highlights': '',
                            'job_describtion': '',
                            'crawltime': time.asctime()
                            }

            if mongodb_instance.insert_one(itemtemplate):
                print("{} {} 数据添加成功!".format(companyname, jobname))
            else:
                print("{} {}数据已存在!".format(companyname, jobname))
    driver.close()


if __name__ == '__main__':
    crawlezhlian()

进入job详情页完善数据库数据

##首先获取数据库url
x = mydoc.find({},{"_id": 0, "joburl": 1})  #得到游标,需要循环获取

import json 
jsontmp = json.dumps({'joburl': 'https://jobs.zhaopin.com/CC702428727J00195978909.htm'})  #对循环获取的数据获取url
jsonx = json.loads(jsontmp)
jsonx.get("joburl")
'https://jobs.zhaopin.com/CC702428727J00195978909.htm'  ##添加到指定的列表等待抓取



###抓取后保存



##



进入公司详情页获取数据

##进入职位详情页面
https://jobs.zhaopin.com/CC493150925J00209948410.htm
x = driver.find_element_by_xpath('//*[@id="root"]/div[3]/div/div/div[2]/div[1]/ul/li[4]')
x.text
招1人


职位亮点
light = driver.find_element_by_xpath('//*[@id="root"]/div[4]/div[1]/div[1]/div[1]/div')
light.text
'五险一金'

职位描述
desc = driver.find_element_by_xpath('//*[@id="root"]/div[4]/div[1]/div[1]/div[2]')
desc.text
'职位描述
技能要求:
Python
职位介绍:
负责共享出行业务运营活动专项的开发工作,主要涉及共享出行优惠、卡券、运营活动等系统的设计和开发,既要保证系统支持需求的灵活性,同时还要保证C端用户的体验以及系统性能和稳定性,是很有挑战性的
技能重点关注:
1.熟悉 python 语言开发,具有在线服务开发经验者优先; 2.熟悉web开发框架(django/tornado/flask),熟悉Linux操作系统及shell编程,能够使用HTML,CSS,JavaScript等基本前端技术; 3.熟悉mysql,redis,mongo等常用数据库,具有数据库开发和设计能力; 4.了解异步框架、集群与负载均衡,消息中间件,容灾备份等技术优先; 5.善于学习,具有良好的分析和解决问题的能力; 6.有全栈开发经验或大型在线服务开发经验优先。'


工作地点
address = driver.find_element_by_xpath('//*[@id="root"]/div[4]/div[1]/div[1]/div[3]/div/span')
address.text
'广东省珠海市唐家湾软件园2号'

获取公司名称,根据公司名称完善已经存储的文档
namecom = driver.find_element_by_xpath('//*[@id="root"]/div[4]/div[2]/div[2]/div[3]/a[1]')
namecom.text
'北京汉克时代科技有限公司'

修改数据库指定数据

update = mydoc.update_one(y, test)
update.modified_count
1   被修改的文档数目


y  符合给条件的文档则修改
test 修改的数据
test = { "$set": {'plan': "1", 'job_describtion': '职位描述
技能要求:
Python
职位介绍:
负责共享出行业务运营活动专项的开发工作,主要涉及共享出行优惠、卡券、运营活动等系统的设计和开发,既要保证系统支持需求的灵活性,同时还要保证C端用户的体验以及系统性能和稳定性,是很有挑战性的
技能重点关注:
1.熟悉 python 语言开发,具有在线服务开发经验者优先; 2.熟悉web开发框架(django/tornado/flask),熟悉Linux操作系统及shell编程,能够使用HTML,CSS,JavaScript等基本前端技术; 3.熟悉mysql,redis,mongo等常用数据库,具有数据库开发和设计能力; 4.了解异步框架、集群与负载均衡,消息中间件,容灾备份等技术优先; 5.善于学习,具有良好的分析和解决问题的能力; 6.有全栈开发经验或大型在线服务开发经验优先。'}}





原文地址:https://www.cnblogs.com/g2thend/p/12452345.html